Skip to content

Using awk to calculate averages

1 min read

Here's a simple little awk script, averages.awk that takes a datafile and returns the average value of each column in that file:-

{ for (i = 1; i <= NF; i++) x[i]+=$i ; j++ } 
END { for ( i=1 ; i<= NF ; i++ ) print x[i]/j }

The first line of the script goes through the datafile keeping a tally of each column in the array x; the number of iterations is stored in the variable j. The variable NFcontains the number of columns read in from the file by awk. The second line is executed at the end and returns the mean average of each column.

The script is simply called from the command line with the last parameter being the name of the datafile from which the averages are to be calculated:-

> awk -f 'averages.awk' datafile.dat
© 2024 Andy Carter