RCzone
RCzone

Reputation: 51

Calculate avg of a row using awk

I have been working a script that calculates avg of a rows by reading input from a txt file

sample text input file input.txt

157361 155687 156158 156830
149610 151824 152353 152027
159195 158490 159030 159243
153222 154227 154578 154390
168761 170078 170044 170107
147166 146477 146735 147678
155745 152142 155141 154140
148860 150040 149223 148246
147239 149693 148144 147990
148045 147987 149466 149535
146945 146206 145681 145852
156559 155188 156274 154962
143169 143798 142753 144045
153814 153320 153732 156621

I'm working on the below awk command:

awk '{sum=0; for(i=0; i<=NF; i++){sum+=$i}; sum/=NF; print sum}' input.txt

i'm getting 156679 as expected result for row1 avg:"somewhere its reading blank space as variable) with the above awk expression.

cal row1 excpected avg would be :(157361+155687+156158+156830)/4 = 156509

Im not getting expected output the avg am geting is wrong expected avg's for the above input file

row1 expected avg :156509
row2 expected avg :151454

Upvotes: 4

Views: 6599

Answers (2)

Gautam
Gautam

Reputation: 1932

Another shorter way to achieve this :

$ sed 's/ /+/g;s/.*/(&)\/4/g' file.txt | bc

Upvotes: 0

ninosanta
ninosanta

Reputation: 67

Field numbers in AWK start from 1 and not from 0. So, in your for loop you need to put i = 1

Doing:

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

I obtained the right results:

156509
151454
158990
154104
169748
147014
154292
149092
148266
148758
146171
155746
143441
154372

Upvotes: 5

Related Questions