linux 中 实现计算一列数据的和
001、awk
[root@pc1 test01]# ls a.txt [root@pc1 test01]# cat a.txt 8 3 2 5 [root@pc1 test01]# awk '{sum += $1} END {print sum}' a.txt ## awk计算第一列数据的和 18

002、paste + bc实现
[root@pc1 test01]# ls a.txt [root@pc1 test01]# cat a.txt ## 测试数据 8 3 2 5 [root@pc1 test01]# paste -d "+" -s a.txt ## -s实现列变行, -d指定连接符 8+3+2+5 [root@pc1 test01]# paste -d "+" -s a.txt | bc ## bc计算 18

。
003、 一般循环方法
[root@pc1 test]# ls a.txt [root@pc1 test]# cat a.txt ## 测试数据 8 3 2 5 [root@pc1 test]# sum=0 [root@pc1 test]# while read i; do sum=$((sum+i)); done < a.txt ## 利用循环累加 [root@pc1 test]# echo $sum 18

。

浙公网安备 33010602011771号