【发布时间】:2013-12-24 02:27:07
【问题描述】:
我有一些 shell 脚本的多行输出,每行一个整数。喜欢:
12
11
55
337
11
34
问题是,我如何用 shell 命令总结这些数字?我试过sum,但它没有达到预期的效果:
<some_shell_scripts> |sum
36373 2
在 ksh 或 bash 中有什么简单的解决方案吗?
【问题讨论】:
我有一些 shell 脚本的多行输出,每行一个整数。喜欢:
12
11
55
337
11
34
问题是,我如何用 shell 命令总结这些数字?我试过sum,但它没有达到预期的效果:
<some_shell_scripts> |sum
36373 2
在 ksh 或 bash 中有什么简单的解决方案吗?
【问题讨论】:
将所有的 '\n' 替换为 '+' 通过 sed 然后 bc
<some_shell_scripts> | sed ':a;N;$!ba;s/\n/+/g' | bc
【讨论】:
sed: 0602-417 The label :a;N;$!ba;s/\n/+/g is greater than eight characters
sed --version 在这里对我不起作用。但看起来我的不是 GNU sed。我的sed 是 AIX 机器自带的。
使用awk,您可以使用类似这样的代码:
$ awk '{count+=$1} END{print count}' file
460
与bash:
sum=0
while read number
do
sum=$(($sum + $number))
done < file
echo $sum
测试:
$ sum=0; while read number; do sum=$(($sum + $number)); done < file
$ echo $sum
460
【讨论】:
【讨论】:
通过管道传递给 awk:
<some_shell_scripts> | awk 'NF{sum+=$1} END {print sum}'
【讨论】: