Blog
Using awk to calculate averages · 5 August 2008, 18:36
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 NF contains 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
— Andy
Posted in: Scripting
Comment
E-mail addresses will not be shown on the site.



