Computing.Net > Forums > Unix > Sorting/Awk Question

Computer Problems? Computing.Net has over 1,000,000 posts about all things technology related! Over 90% answered within 24 hours! Click here to start participating now! Also, be sure to check out the New User Guide.

Sorting/Awk Question

Reply to Message Icon

Name: lazypeterson
Date: March 17, 2009 at 10:16:06 Pacific
OS: Linux i686
Subcategory: General
Comment:

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



Sponsored Link
Ads by Google

Response Number 1
Name: James Boothe
Date: March 24, 2009 at 13:32:55 Pacific
Reply:

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
}' awkgrades

Name     Exam1 Exam2 Exam3 Total Grade
Alice      24    14    10    48    F
Beth       36    30    20    86    B
Cindy      44    33    22    99    A


0
Reply to Message Icon

Related Posts

See More


Simple shell script(csh) ... Comparing 2 files column...


Use following form to reply to current message:

Login or Register to Reply
LoginRegister


Sponsored links

Ads by Google


Results for: Sorting/Awk Question

awk question www.computing.net/answers/unix/awk-question/6685.html

AWK Question www.computing.net/answers/unix/awk-question/4512.html

awk question www.computing.net/answers/unix/awk-question/7115.html