Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
My goal is to have the three final grades ($2+$3+$4) outputted in descending order. Is there a way to incorporate sort into awk so that it sorts the grades in that manner before printing to the screen? Thanks.
#!/bin/csh awk 'BEGIN { print "Name Exam1 Exam2 Exam 3 Total Grade" }' awk '{if ($2+$3+$4<50){grade="F"}else if ($2+$3+$4>49 && $2+$3+$4<65){grade="D"}else if ($2+$3+$4>64 && $2+$3+$4<80){grade="C"}else if ($2+$3+$4>79 && $2+$3+$4<90){grade="B"}else{grade="A"}}{print $0, " ", $2+$3+$4, " ", grade;}' grades

With just 3 columns to sort, an if-else series will do it.
I chose to assign the 3 grades to variables a b c, as that might be a little easier to work with instead of $2 $3 $4, and this gives your code some isolation if the input format were to change on you. Also, I prefer to total the 3 grades just once.
And you do not have to keep checking for a range of grades, just an increasing lower limit.
The printf command defines a "format" containing 6 variables.
awk '\
BEGIN {print "Name Exam1 Exam2 Exam3 Total Grade"}
{
a=$2
b=$3
c=$4
tot=a+b+c#-- sort the 3 exam grades --
if (a<b)
if (b<c)
{e1=a;e2=b;e3=c}
else
if (a<c)
{e1=a;e2=c;e3=b}
else
{e1=c;e2=a;e3=b}
else
if (c<b)
{e1=c;e2=b;e3=a}
else
if (a<c)
{e1=b;e2=a;e3=c}
else
{e1=b;e2=c;e3=a}
#----------------------------if (tot<50) grade="F"
else
if (tot<65) grade="D"
else
if (tot<80) grade="C"
else
if (tot<90) grade="B"
else
grade="A"
printf "%-8s %4d %4d %4d %4d %s\n",$1,e3,e2,e1,tot,grade
}' awkgradesName Exam1 Exam2 Exam3 Total Grade
Alice 24 14 10 48 F
Beth 36 30 20 86 B
Cindy 44 33 22 99 A

![]() |
Simple shell script(csh) ...
|
Comparing 2 files column...
|
| Login or Register to Reply | |
| Login | Register |
| Ads by Google |