在Stackoverflow上看到的一则问答,之前有收集过一些,在里面都包括了,还扩充了不少,值得学习,就此记录如下(实例):
# cat num.txt
1
2
3
4
5
6
7
8
9
10
# awk '{s+=$1} END {print s}' num.txt
55
# paste -s -d+ num.txt | bc
55
# cat num.txt | python -c "import sys; print sum(int(l) for l in sys.stdin)"
55
# cat num.txt | perl -lpe '$c+=$_}{$_=$c'
55
# cat num.txt | xargs | sed -e 's/ /+/g' | bc
55
# cat num.txt | xargs
1 2 3 4 5 6 7 8 9 10
# cat num.txt | perl -MList::Util -le 'print List::Util::sum(<>)'
55
# sed 's/^/.+/' num.txt | bc | tail -1
55
# sed 's/^/.+/' num.txt | bc
1
3
6
10
15
21
28
36
45
55
最方便的还是awk啊,其次就是sed/xargs加上bc的组合了,Perl、Python什么的也不错。
1.paste命令
Using existing file:
paste -sd+ infile | bc
Using stdin:
<cmd> | paste -sd+ | bc
Edit: With some paste implementations you need to be more explicit when reading from stdin:
<cmd> | paste -sd+ - | bc
2.awk命令(效率高于上面的paste命令)
I like the chosen answer. However, it tends to be slower than awk since 2 tools are needed to do the job.
$ 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
3.先cat然后tr最后管道传给bc命令
You can use bc (calculator). Assuming your file with #s is called "n":
$ cat n
1
2
3
$ (cat n | tr "\012" "+" ; echo "0") | bc
6
The tr changes all newlines to "+"; then we append 0 after the last plus, then we pipe the expression (1+2+3+0) to the calculator
4.Perl方法
Or, if you are OK with using awk or perl, here's a Perl one-liner:
$perl -nle '$sum += $_ } END { print $sum' n
6
5.将循环写在单行
while read -r num; do ((sum += num)); done < inputfile; echo $sum
《“用一行shell命令做累加操作”》 有 1 条评论
awk实现数值累加
https://coolnull.com/3107.html
awk: 计算一列数字的sum
https://www.chedong.com/blog/archives/000682.html