Home > Software design >  awk script to find the average of a particular row
awk script to find the average of a particular row

Time:12-14

Is it possible with awk to find a average of a certain row ? For example the txt file (average.txt) contains:

2 5 10
1 5 5
1 5 10

So I want to find only first row average: 5,666667.

I tried to do it this way: awk 'NR==1 {sum =NF} END {print(sum/NF)}' average.txt but the output is wrong: 1

CodePudding user response:

Like this:

$ awk 'NR==1{for (i=1; i<=NF; i  ) sum =$i}END{print sum/NF}' file
5.66667

CodePudding user response:

I want to explain what your code is actually doing. NF built-in variable is holding number of files in current line thus for file average.txt

2 5 10
1 5 5
1 5 10

code

awk 'NR==1 {sum =NF} END {print(sum/NF)}' average.txt

does for fist line increase sum by number of fields (3 for provided file) and then after processing all files does print that value divided by number of fields in last line, in other words your code does compute ratio of number of fields in 1st field and number of fields in last line. If you want to know more about NF then read 8 Powerful Awk Built-in Variables – FS, OFS, RS, ORS, NR, NF, FILENAME, FNR

CodePudding user response:

You can loop through all fields and sum up all the values.

If you only want to process the first record, you can print the value directly and then exit awk.

To prevent a division by zero exception, you can check if the number of fields is > 0

awk 'NR==1 && NF>0 {for (i=1; i<=NF; i  ) sum =$i; print sum/NF; exit}' average.txt

CodePudding user response:

Yet another solution. It seems useless for me to loop on every line if only the first is the one you are interested in.

Instead, just head -1 the file containing your data, like so (here, the file is called test):

head -1 test | awk '{for (i=1; i<=NF; i  ) sum =$i; print sum/NF}'

Here, the awk command is basically copy/pasta from other answers, but without all the NR=1 stuff.

  • Related