linux 中如何求每列的和及平均值

 

001、求每列的和

root@PC1:/home/test2# ls
a.txt
root@PC1:/home/test2# cat a.txt     ## 测试数据
3 5 2 4
1 3 5 5
2 3 8 3
root@PC1:/home/test2# for i in $(seq $(head -n 1 a.txt | awk '{print NF}')); do awk -v a=$i '{sum += $a} END {print sum}' a.txt >> sum.txt; done ## 求每列的和
root@PC1:/home/test2# ls
a.txt  sum.txt
root@PC1:/home/test2# cat sum.txt   ## 计算结果
6
11
15
12

 

 

 

001、求每列的平均值

root@PC1:/home/test2# ls
a.txt
root@PC1:/home/test2# cat a.txt
3 5 2 4
1 3 5 5
2 3 8 3
root@PC1:/home/test2# for i in $(seq $(head -n 1 a.txt | awk '{print NF}')); do awk -v a=$i '{sum += $a} END {print sum/NR}' a.txt >> mean.txt; done
root@PC1:/home/test2# ls
a.txt  mean.txt
root@PC1:/home/test2# cat mean.txt     ## 每列的平均值结果
2
3.66667
5
4

 

 

posted @ 2022-06-20 17:46  小鲨鱼2018  阅读(643)  评论(0编辑  收藏  举报