The awk user command is made to read a file and check each column, one by one.
We need to compute the average of students’ marks and to display the total of their average.
Let’s go.
Explanation
In the BEGIN pattern we specify the separator with the FS builtin variable. In our case, it will be the default one: " " (the space character).
In the dev pattern, we are going to retrieve marks of each student and make an average of them.
For that, we use a variable as an array, so we can retrieve data from the line where we are, with the NR builtin variable.
For example, with the first line, we can retrieve the name of each student with:
name[NR] = $1;
And this for every line of our file.
Notice that with awk, the first element is 1 and not 0.
We do the same for the average and the total.
In the END pattern, we’re going to print each student with its own average.
We’re displaying the total as well.
Code
students.txt
John 5 12 8
Akio 15 16 14
Ortallia 2 8 6
Markus 11 9 12
bp7.awk
#!/bin/awk
# Begin
BEGIN {
FS=" ";
}
# Dev
{
name[NR] = $1;
average[NR] = ($2 + $3 + $4) / 3;
total += average[NR]
}
# End
END {
print "We saw " FNR " students, their average is:\n";
i = 1;
while (i <= FNR) {
printf("%-10s %.2f\n", name[i] , average[i++]);
}
print "\nTotal average = ", total/FNR;
}
Executing
$ awk -f bp7.awk students.txt
Output
We saw 4 students, their average is:
John 8.33
Akio 15.00
Ortallia 5.33
Markus 10.67
Total average = 9.83333
Finally
Our students are now happy to know their average.
Well done, you’ve made it.