我正在寻找一个命令,它将接受(作为输入)多行文本,每行包含一个整数,并输出这些整数的和。
作为一点背景知识,我有一个日志文件,其中包括计时测量。通过grepping的相关行和一点sed重新格式化,我可以列出该文件中的所有时间。我想算出总数。我可以将这个中间输出输出到任何命令,以便进行最终求和。我过去一直使用expr,但除非它在RPN模式下运行,否则我不认为它会处理这个问题(即使这样也会很棘手)。
我怎样才能得到整数的和?
我正在寻找一个命令,它将接受(作为输入)多行文本,每行包含一个整数,并输出这些整数的和。
作为一点背景知识,我有一个日志文件,其中包括计时测量。通过grepping的相关行和一点sed重新格式化,我可以列出该文件中的所有时间。我想算出总数。我可以将这个中间输出输出到任何命令,以便进行最终求和。我过去一直使用expr,但除非它在RPN模式下运行,否则我不认为它会处理这个问题(即使这样也会很棘手)。
我怎样才能得到整数的和?
当前回答
不能避免提交这个,这是最通用的方法来解决这个问题,请查看:
jot 1000000 | sed '2,$s/$/+/;$s/$/p/' | dc
在这里可以找到,我是OP,答案来自观众:
最优雅的unix shell一行程序和任意精度的数字列表?
以下是它相对于awk、bc、perl、GNU的datamash及其朋友的特殊优势:
它使用任何Unix环境中常见的标准实用程序 它不依赖于缓冲,因此不会因为很长的输入而阻塞。 这意味着没有特定的精度限制-或整数大小的问题-你好AWK的朋友! 如果需要添加浮点数,则不需要不同的代码。 理论上它可以在最少的环境中不受阻碍地运行
其他回答
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'
perl -lne '$x += $_; END { print $x; }' < infile.txt
c++(简体):
echo {1..10} | scc 'WRL n+=$0; n'
SCC项目- http://volnitsky.com/project/scc/
SCC是shell提示符下的c++代码段求值器
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()
《球拍》中的一句俏皮话:
racket -e '(define (g) (define i (read)) (if (eof-object? i) empty (cons i (g)))) (foldr + 0 (g))' < numlist.txt