1
votes

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
2
You can remove the m vairable and its assignment completely as you never use it. - 123

2 Answers

4
votes

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
votes

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