我正在寻找一个命令,它将接受(作为输入)多行文本,每行包含一个整数,并输出这些整数的和。

作为一点背景知识,我有一个日志文件,其中包括计时测量。通过grepping的相关行和一点sed重新格式化,我可以列出该文件中的所有时间。我想算出总数。我可以将这个中间输出输出到任何命令,以便进行最终求和。我过去一直使用expr,但除非它在RPN模式下运行,否则我不认为它会处理这个问题(即使这样也会很棘手)。

我怎样才能得到整数的和?


当前回答

粘贴通常合并多个文件的行,但它也可以用于将文件的各个行转换为一行。分隔符标志允许您将x+x类型的方程传递给bc。

paste -s -d+ infile | bc

或者,当从stdin管道时,

<commands> | paste -s -d+ - | bc

其他回答

我的版本:

seq -5 10 | xargs printf "- - %s" | xargs  | bc

提前为反勾号(“'”)的可读性道歉,但这些在shell中工作,而不是bash,因此更易于粘贴。如果你使用一个接受它的shell, $(command…)格式比' command…所以为了你的理智,请随意修改。

我在bashrc中有一个简单的函数,它将使用awk来计算一些简单的数学项

calc(){
  awk 'BEGIN{print '"$@"' }'
}

这将做 +,-,*,/,^,%, √6,罪恶,因为,括号……(取决于你的awk版本)…你甚至可以用printf和格式化浮点输出,但这是我通常需要的

对于这个特定的问题,我将对每一行简单地这样做:

calc `echo "$@"|tr " " "+"`

所以对每一行求和的代码块看起来像这样:

while read LINE || [ "$LINE" ]; do
  calc `echo "$LINE"|tr " " "+"` #you may want to filter out some lines with a case statement here
done

如果你想逐行求和的话。但是,对于数据文件中的每个数字的总数

VARS=`<datafile`
calc `echo ${VARS// /+}`

顺便说一句,如果我需要在桌面上快速做一些事情,我使用这个:

xcalc() { 
  A=`calc "$@"`
  A=`Xdialog --stdout --inputbox "Simple calculator" 0 0 $A`
  [ $A ] && xcalc $A
}

您可以使用num-utils,尽管对于您所需要的来说它可能太过了。这是一组用于在shell中操作数字的程序,可以做一些漂亮的事情,当然包括将它们相加。它有点过时了,但它们仍然有效,如果你需要做更多的事情,它们可以很有用。

https://suso.suso.org/programs/num-utils/index.phtml

使用起来非常简单:

$ seq 10 | numsum
55

但内存不足,无法输入大量数据。

$ seq 100000000 | numsum
Terminado (killed)

金桥:

seq 10 | jq -s 'add' # 'add' is equivalent to 'reduce .[] as $item (0; . + $item)'
dc -f infile -e '[+z1<r]srz1<rp'

注意,带负号前缀的负数应该转换为dc,因为它使用_ prefix而不是- prefix。例如,通过tr '-' '_' | dc -f- -e '…'。

编辑:由于这个答案获得了很多“晦涩难懂”的投票,下面是一个详细的解释:

表达式[+z1<r]srz1<rp的作用如下:

[   interpret everything to the next ] as a string
  +   push two values off the stack, add them and push the result
  z   push the current stack depth
  1   push one
  <r  pop two values and execute register r if the original top-of-stack (1)
      is smaller
]   end of the string, will push the whole thing to the stack
sr  pop a value (the string above) and store it in register r
z   push the current stack depth again
1   push 1
<r  pop two values and execute register r if the original top-of-stack (1)
    is smaller
p   print the current top-of-stack

伪代码:

定义"add_top_of_stack"为: 从堆栈中删除顶部的两个值,并将结果添加回来 如果堆栈有两个或两个以上的值,递归地运行"add_top_of_stack" 如果堆栈有两个或两个以上的值,执行"add_top_of_stack" 打印结果,现在堆栈中只剩下一项

为了真正理解dc的简单和强大,这里有一个工作的Python脚本,它实现了dc的一些命令,并执行上述命令的Python版本:

### Implement some commands from dc
registers = {'r': None}
stack = []
def add():
    stack.append(stack.pop() + stack.pop())
def z():
    stack.append(len(stack))
def less(reg):
    if stack.pop() < stack.pop():
        registers[reg]()
def store(reg):
    registers[reg] = stack.pop()
def p():
    print stack[-1]

### Python version of the dc command above

# The equivalent to -f: read a file and push every line to the stack
import fileinput
for line in fileinput.input():
    stack.append(int(line.strip()))

def cmd():
    add()
    z()
    stack.append(1)
    less('r')

stack.append(cmd)
store('r')
z()
stack.append(1)
less('r')
p()