我想要一个bash命令,我可以管道将一列数字相加。我只是想要一个快速的一行程序,基本上是这样做的:
cat FileWithColumnOfNumbers.txt | sum
我想要一个bash命令,我可以管道将一列数字相加。我只是想要一个快速的一行程序,基本上是这样做的:
cat FileWithColumnOfNumbers.txt | sum
当前回答
[root@pentest3r ~]# (find / -xdev -size +1024M) | (while read a ; do aa=$(du -sh $a | cut -d "." -f1 ); o=$(( $o+$aa )); done; echo "$o";)
其他回答
使用for循环遍历你的文件…
sum=0; for x in `cat <your-file>`; do let sum+=x; done; echo $sum
使用现有文件:
paste -sd+ infile | bc
使用stdin:
<cmd> | paste -sd+ | bc
编辑: 对于一些粘贴实现,你需要更明确地从stdin读取:
<cmd> |粘贴-sd+ - | BC
选择使用:
-s (serial) -将所有行合并为一行 -d -使用非默认分隔符(在本例中为字符+)
while read -r num; do ((sum += num)); done < inputfile; echo $sum
我喜欢选定的答案。然而,它往往比awk慢,因为需要两个工具来完成这项工作。
$ wc -l file
49999998 file
$ time paste -sd+ file | bc
1448700364
real 1m36.960s
user 1m24.515s
sys 0m1.772s
$ time awk '{s+=$1}END{print s}' file
1448700364
real 0m45.476s
user 0m40.756s
sys 0m0.287s
如果你安装了ruby
cat FileWithColumnOfNumbers.txt | xargs ruby -e "puts ARGV.map(&:to_i).inject(&:+)"