nightclone nightclone - 2 months ago 6
Linux Question

Using awk to calculate and print average scores for each row

Use the awk command


  1. Using the grades.txt file print out the first and last name of each student and
    calculate/print the grade in percentage that they currently have (assuming equal
    weights for each assignment).



grades.txt file

FN LN Lab HW1 HW2 HW3 HW4
Ryan Slaven 1 1 0 1 1
Jephthah Eustathios 0 1 0 1 0
Andreas Saša 1 0 1 0 1
Godofredo Gerard 1 1 1 1 1
Edwin Babur 1 0 1 1 1
Ahmad Marin 0 0 0 0 0
Jett Marko 1 1 0 1 1


My answer for it is:

awk '{sum=0;for(i=3;i<=NF;i++) sum+=$i; print $1, $2, (NF>2?sum/(NF-2):0)*100}' grades.txt


However, for the output next to FN and LN it shows 0. How could I remove the 0, or make it say "Average"? Alternatively, how could I delete the row?

Also, is there a better way to solve the question?

Answer
awk 'NR == 1 { print $1, $2, "Average"; next }    # Print a heading row
     NF > 2  { sum=0; for (i=3; i<=NF; i++) sum+=$i; print $1, $2, (sum/(NF-2))*100 }' \
     grades.txt

Simply process the first row differently; the next skips the rest of the script on the first line. For other rows with more than two fields, print the name and average. It would be possible to report on rows where NF <= 2 if required.

Sample output:

FN LN Average
Ryan Slaven 80
Jephthah Eustathios 40
Andreas Saša 60
Godofredo Gerard 100
Edwin Babur 80
Ahmad Marin 0
Jett Marko 80
Comments