This is the website of Andy Carter a Textpattern and Drupal web developer living in the Steel city.

Using awk to calculate averages

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

You might be interested in the following


Comment

Want to comment?

To comment you'll need to provide an e-mail address. Don't worry all e-mail addresses are kept private and will never be shown on this site or distributed to others.

Don't forget the http:// part

You'll need to preview your comment before it can be submitted; this is to help prevent spam and to give you a chance to review your comment before it gets posted on the site.

Comment formatting:

_emphasis_
*strong*
??citation??
-deleted text-
+inserted text+
^superscript^

Hyperlink:
"link text":http://link.com/

To define an acronym:
ABC(Always Be Closing)

Note: All (X)HTML tags will be escaped.