Average from different columns in shell script

☆樱花仙子☆ 提交于 2019-12-24 11:35:20

问题


I have a datafile with 10 columns as given below

ifile.txt
2  4  4  2  1  2  2  4  2  1
3  3  1  5  3  3  4  5  3  3
4  3  3  2  2  1  2  3  4  2
5  3  1  3  1  2  4  5  6  8

I want to add 11th column which will show the average of each rows along 10 columns. i.e. AVE(2 4 4 2 1 2 2 4 2 1) and so on. Though my following script is working well, but I would like to make it more simpler and short. I appreciate, in advance, for any kind help or suggestions in this regard.

awk '{for(i=1;i<=NF;i++){s+=$i;ss+=$i}m=s/NF;$(NF+1)=ss/NF;s=ss=0}1' ifile.txt

回答1:


This should work

awk '{for(i=1;i<=NF;i++)x+=$i;$(NF+1)=x/NF;x=0}1' file

For each field you add the value to x in the loop.

Next you set field 11 to the sum in xdivided by the number of fields NF.

Reset x to zero for the next line.

1 equates to true and performs the default action in awk which is to print the line.




回答2:


is this helping

awk '{for(i=1;i<=NF;i++)s+=$i;print $0,s/NF;s=0}' ifile.txt

or

awk '{for(i=1;i<=NF;i++)ss+=$i;$(NF+1)=ss/NF;ss=0}1' ifile.txt


来源:https://stackoverflow.com/questions/31557317/average-from-different-columns-in-shell-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!