awk Useful one-liners - calculating average from a CSV etc Compute the average of values in a column from tabular data


Example

Given a file using ; as a column delimiter. We compute the mean of the values in the second column with the following program, the provided input is the list of grades of a student group:

awk -F';' '{ sum += $2 } END { print(sum / NR) }' <<EOF
Alice;2
Victor;1
Barbara;1
Casper;4
Deborah;0
Ernest;1
Fabiola;4
Giuseppe;4
EOF

The output of this program is 2.125.

Remember that NR holds the number of the line being processed, in the END block it therefore hold the total number of lines in the file.

Remember that in many applications (monitoring, statistics), the median is a much more useful information. See the corresponding example.