2

My file is as below; I want to display those records of students whose percentage is above 80.

Studid    StudName     Asp.Net   DBMS     Unix
   1       Ani         75        62       80
   2       George      90        95       82
   3       Jake        45        30       40
   4       Dennie      89        92       90

so I used following code:

awk '(($3+$4+$5)/3)>80 {print}' stud

It works, but I want to assign these columns into variable and then want to display output. So I tried below code, but it didn't work

awk 'total=$3+$4+$5, per=total/3, per>80 {print}' stud

any solution with variables?

  • not sure why you need to assign them into variable.. awk 'NR==1 || ($3+$4+$5)/3 > 80' stud looks simple and easy... – Sundeep Oct 2 '16 at 10:30
5

You can move the logic from the rule section into an action

awk '{total=$3+$4+$5; per=total/3; if (per>80) print}' stud
   2       George      90        95       82
   4       Dennie      89        92       90

Note that this attempts to evaluate the column headers arithmetically - which "works" because in awk, non-numeric fields are treated as zero when you try to do arithmetic on them - but would cause the header line to be printed if, for example, you changed the test to per<80. Better IMHO would be to either explicitly skip the header line using a next action for the rule NR==1

awk 'NR==1 {next} {total=$3+$4+$5; per=total/3; if (per>80) print}' stud
   2       George      90        95       82
   4       Dennie      89        92       90

or, if you want the header, explicitly print it

awk 'NR==1 {print; next} {total=$3+$4+$5; per=total/3; if (per>80) print}' stud
Studid    StudName     Asp.Net   DBMS     Unix
   2       George      90        95       82
   4       Dennie      89        92       90
  • will you please specify the meaning of {print;next} statement. Actually i want to skip first line in some queries so i wrote NR>1 but it didn't work. – Dip Oct 1 '16 at 9:22
  • @Dip please see updated answer – steeldriver Oct 1 '16 at 12:57
  • You can also do some code golfing and say {total=$3+$4+$5; per=total/3} (per>80). That last part will trigger the print if it evaluates to True. – fedorqui Oct 1 '16 at 16:33
2

Try:

awk ' 
# if /^Studid/ is matched move to the next record (row) of the input text
/^Studid/ { next }
{               
    total=$3+$4+$5
    per=total/3
    if (per > 80)  
        print 
}' stud

output

   2       George      90        95       82
   4       Dennie      89        92       90

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.