给定files.txt中的文件列表,我可以得到它们的大小列表,如下所示:
cat files.txt | xargs ls -l | cut -c 23-30
这会产生这样的结果:
151552
319488
1536000
225280
我怎样才能得到所有这些数字的总数呢?
给定files.txt中的文件列表,我可以得到它们的大小列表,如下所示:
cat files.txt | xargs ls -l | cut -c 23-30
这会产生这样的结果:
151552
319488
1536000
225280
我怎样才能得到所有这些数字的总数呢?
当前回答
粘贴不是必需的。只要files.txt包含一个或多个有效文件名,就可以执行以下操作:
<files.txt xargs stat -c %s | paste -sd+ | bc
如果没有文件,Cat不需要插入0。如果没有管道,也许在脚本中更方便,您可以使用:
(xargs -a files.txt stat -c %s || echo 0) | paste -sd+ | bc
其他回答
如果您没有安装BC,请尝试
echo $(( $(... | paste -sd+ -) ))
而不是
... | paste -sd+ - | bc
$() <——返回执行命令的值
$((1+2)) <——返回求值结果
Echo <——将它回显到屏幕
... | paste -sd+ - | bc
是我找到的最短的一个(来自UNIX命令行博客)。
编辑:增加了-参数的可移植性,谢谢@Dogbert和@Owen。
我会用“du”来代替。
$ cat files.txt | xargs du -c | tail -1
4480 total
如果你只想要数字:
cat files.txt | xargs du -c | tail -1 | awk '{print $1}'
如果你有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
灵感:有没有一种方法可以在一个命令中获得一组数字的最小值、最大值、中值和平均值?
纯bash
total=0; for i in $(cat files.txt | xargs ls -l | cut -c 23-30); do
total=$(( $total + $i )); done; echo $total