7.6.1. Averaging Student Grades
Let's look at another example, one in which we sum a series of
student grades and then calculate the average. Here's what
the input file looks like:
john 85 92 78 94 88
andrea 89 90 75 90 86
jasper 84 88 80 92 84
There are five grades following the student's name.
Here is the script that will give us each student's
average:
# average five grades
{ total = $2 + $3 + $4 + $5 + $6
avg = total / 5
print $1, avg }
This script adds together fields 2 through 6 to get
the sum total of the five grades.
The value of total is divided by 5 and assigned
to the variable avg. ("/" is the operator for
division.) The print statement
outputs the student's name and average.
Note that we could have skipped the assignment of avg
and instead calculated the average as part of the print
statement, as follows:
print $1, total / 5
This script shows how easy it is
to write programs in awk.
Awk parses the input into fields and records.
You are spared having to read individual characters and declaring data
types. Awk does this for you, automatically.
Let's see a sample run of the script that calculates student
averages:
$ awk -f grades.awk grades
john 87.4
andrea 86
jasper 85.6