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

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

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


当前回答

我对现有的答案做了一个快速的基准测试

只使用标准工具(不好意思像lua或rocket), 都是真正的俏皮话, 能够添加大量的数字(1亿),和 速度很快(我忽略了那些超过一分钟的)。

我总是把数字从1亿加到1亿,这在我的机器上可以在一分钟内完成几个解决方案。

以下是调查结果:

Python

:; seq 100000000 | python -c 'import sys; print sum(map(int, sys.stdin))'
5000000050000000
# 30s
:; seq 100000000 | python -c 'import sys; print sum(int(s) for s in sys.stdin)'
5000000050000000
# 38s
:; seq 100000000 | python3 -c 'import sys; print(sum(int(s) for s in sys.stdin))'
5000000050000000
# 27s
:; seq 100000000 | python3 -c 'import sys; print(sum(map(int, sys.stdin)))'
5000000050000000
# 22s
:; seq 100000000 | pypy -c 'import sys; print(sum(map(int, sys.stdin)))'
5000000050000000
# 11s
:; seq 100000000 | pypy -c 'import sys; print(sum(int(s) for s in sys.stdin))'
5000000050000000
# 11s

Awk

:; seq 100000000 | awk '{s+=$1} END {print s}'
5000000050000000
# 22s

膏& Bc

我的机器内存不足了。它适用于一半大小的输入(5000万个数字):

:; seq 50000000 | paste -s -d+ - | bc
1250000025000000
# 17s
:; seq 50000001 100000000 | paste -s -d+ - | bc
3750000025000000
# 18s

所以我猜1亿个数字大约需要35秒。

Perl

:; seq 100000000 | perl -lne '$x += $_; END { print $x; }'
5000000050000000
# 15s
:; seq 100000000 | perl -e 'map {$x += $_} <> and print $x'
5000000050000000
# 48s

Ruby

:; seq 100000000 | ruby -e "puts ARGF.map(&:to_i).inject(&:+)"
5000000050000000
# 30s

C

为了比较起见,我编译了C版本并进行了测试,只是为了了解基于工具的解决方案有多慢。

#include <stdio.h>
int main(int argc, char** argv) {
    long sum = 0;
    long i = 0;
    while(scanf("%ld", &i) == 1) {
        sum = sum + i;
    }
    printf("%ld\n", sum);
    return 0;
}

 

:; seq 100000000 | ./a.out 
5000000050000000
# 8s

结论

C当然是用8秒最快的,但Pypy解决方案只增加了很少的开销,约为11秒的30%。但是,公平地说,Pypy并不是完全标准的。大多数人只安装了CPython,它非常慢(22秒),和流行的Awk解决方案一样快。

基于标准工具的最快解决方案是Perl(15秒)。

其他回答

Rebol中的一句话:

rebol -q --do 's: 0 while [d: input] [s: s + to-integer d] print s' < infile.txt

不幸的是,上述在Rebol 3中还不能工作(INPUT不能流化STDIN)。

下面是一个在Rebol 3中也适用的临时解决方案:

rebol -q --do 's: 0 foreach n to-block read %infile.txt [s: s + n] print s'

BASH解决方案,如果你想让它成为一个命令(例如,如果你需要经常这样做):

addnums () {
  local total=0
  while read val; do
    (( total += val ))
  done
  echo $total
}

然后使用:

addnums < /tmp/nums

你可以在python中这样做,如果你觉得舒服的话:

没有测试,只是输入:

out = open("filename").read();
lines = out.split('\n')
ints = map(int, lines)
s = sum(ints)
print s

Sebastian指出了一个单行脚本:

cat filename | python -c"from fileinput import input; print sum(map(int, input()))"
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()

纯粹而简短的敲打。

f=$(cat numbers.txt)
echo $(( ${f//$'\n'/+} ))