UNIX & GNU/Linux - awk - Read a file and computing the average of students' marks

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. smiley

Comments

Comment: 

What if I'm trying to calculate a table in where i have a corresponding letter for each average in a column like this
Name Type Score Type Score Type Score Type Score
Jones Q 90 H 100 E 74 F 74
Bob Q 80 h 95 e 82 F 93
John q Q 70 H 99 E 87 f 98
Xiang q 90 H 80 E 83 F 70
Frank q 80 H 85 E 86 F 83

How would I print the average for all Q's H's E's and F's ?
I've been writting code all day and can't figure it out...

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.