给定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
我怎样才能得到所有这些数字的总数呢?
当前回答
纯bash
total=0; for i in $(cat files.txt | xargs ls -l | cut -c 23-30); do
total=$(( $total + $i )); done; echo $total
其他回答
这里是我的
cat files.txt | xargs ls -l | cut -c 23-30 | sed -e :a -e '$!N;s/\n/+/;ta' | bc
纯bash
total=0; for i in $(cat files.txt | xargs ls -l | cut -c 23-30); do
total=$(( $total + $i )); done; echo $total
粘贴不是必需的。只要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
如果你只想使用shell脚本而不使用awk或其他解释器,你可以使用下面的脚本:
#!/bin/bash
total=0
for number in `cat files.txt | xargs ls -l | cut -c 23-30`; do
let total=$total+$number
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
灵感:有没有一种方法可以在一个命令中获得一组数字的最小值、最大值、中值和平均值?