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

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

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


当前回答

bash的工作原理如下:

I=0

for N in `cat numbers.txt`
do
    I=`expr $I + $N`
done

echo $I

其他回答

一个简单的解决方案是编写一个程序来为你做这件事。这可能在python中很快就可以完成,类似于:

sum = 0
file = open("numbers.txt","R")
for line in file.readlines(): sum+=int(line)
file.close()
print sum

我还没有测试该代码,但它看起来是正确的。只需将numbers.txt更改为文件名,将代码保存到一个名为sum.py的文件中,并在控制台中键入"python sum.py"

你可以在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()))"

更新的基准

所以我合成了随机分布的100mn个整数

之间的

0^0 - 1 

and

8^8 - 1

代码生成器

mawk2 '
BEGIN {
     __=_=((_+=_^=_<_)+(__=_*_*_))^(___=__)
     srand()
     ___^=___
     do  { 
           print int(rand()*___) 
  
     } while(--_)  }' | pvE9 > test_large_int_100mil_001.txt

     out9:  795MiB 0:00:11 [69.0MiB/s] [69.0MiB/s] [ <=> ]

  f='test_large_int_100mil_001.txt'
  wc5 < "${f}"

    rows = 100000000. | UTF8 chars = 833771780. | bytes = 833771780.

最后一位的奇/偶分布

Odd  49,992,332
Even 50,007,668

AWK -最快的,有很大的优势(可能C更快,我不知道)

in0:  795MiB 0:00:07 [ 103MiB/s] [ 103MiB/s] [============>] 100%            
( pvE 0.1 in0 < "${f}" | mawk2 '{ _+=$__ } END { print _ }'; )  

 7.64s user 0.35s system 103% cpu 7.727 total
     1  838885279378716

Perl -相当不错

 in0:  795MiB 0:00:10 [77.6MiB/s] [77.6MiB/s] [==============>] 100%            
( pvE 0.1 in0 < "${f}" | perl -lne '$x += $_; END { print $x; }'; )  
 
10.16s user 0.37s system 102% cpu 10.268 total

     1  838885279378716

Python3——稍微落后于Perl

 in0:  795MiB 0:00:11 [71.5MiB/s] [71.5MiB/s] [===========>] 100%            
( pvE 0.1 in0 < "${f}" | python3 -c ; )  

 11.00s user 0.43s system 102% cpu 11.140 total
     1  838885279378716

RUBY -不错

 in0:  795MiB 0:00:13 [61.0MiB/s] [61.0MiB/s] [===========>] 100%            
( pvE 0.1 in0 < "${f}" | ruby -e 'puts ARGF.map(&:to_i).inject(&:+)'; )  
15.30s user 0.70s system 101% cpu 15.757 total

     1  838885279378716

JQ -慢

 in0:  795MiB 0:00:25 [31.1MiB/s] [31.1MiB/s] [========>] 100%            
( pvE 0.1 in0 < "${f}" | jq -s 'add'; )  

 36.95s user 1.09s system 100% cpu 37.840 total

     1  838885279378716

DC

- ( had to kill it after no response in minutes)
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()

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

paste -s -d+ infile | bc

或者,当从stdin管道时,

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