给定files.txt中的文件列表,我可以得到它们的大小列表,如下所示:

cat files.txt | xargs ls -l | cut -c 23-30

这会产生这样的结果:

  151552
  319488
 1536000
  225280

我怎样才能得到所有这些数字的总数呢?


当前回答

纯bash

total=0; for i in $(cat files.txt | xargs ls -l | cut -c 23-30); do 
total=$(( $total + $i )); done; echo $total

其他回答

当管道的开始可以产生0行时,最流行的答案是不正确的,因为它最终输出的是0而不是什么。你可以通过总是加0来得到正确的行为:

... | (cat && echo 0) |粘贴-sd+ - | BC

... | paste -sd+ - | bc

是我找到的最短的一个(来自UNIX命令行博客)。

编辑:增加了-参数的可移植性,谢谢@Dogbert和@Owen。

这里是

cat files.txt | xargs ls -l | cut -c 23-30 | 
  awk '{total = total + $1}END{print total}'

纯bash

total=0; for i in $(cat files.txt | xargs ls -l | cut -c 23-30); do 
total=$(( $total + $i )); done; echo $total

如果你有R,你可以用:

> ... | Rscript -e 'print(sum(scan("stdin")));'
Read 4 items
[1] 2232320

因为我对R很熟悉,所以我实际上有几个类似的别名,所以我可以在bash中使用它们,而不必记住这个语法。例如:

alias Rsum=$'Rscript -e \'print(sum(scan("stdin")));\''

我该怎么做

> ... | Rsum
Read 4 items
[1] 2232320

灵感:有没有一种方法可以在一个命令中获得一组数字的最小值、最大值、中值和平均值?