I have a text file containing a list of student grades:

Andrew cooking A
Andrew cooking B
Andrew computing F
Steven java C
Steven python E
Ben C++ D
Ben python C
Jamie java E
Jamie C++ E
Jamie C++ B
Jamie python E
Gerry python E
Phil python F

I am trying to use the grep command to show all python results, sorted from best to worst grade. The file is called a.txt. I have tried grep python a.txt | sort -d which doesn't work, so I was looking for a bit of help on this. Thanks

  • 1
    You need to key the sort on the grade (third) field e.g. sort -dk3 – steeldriver Feb 6 '15 at 2:28
  • Yeah i just worked this out and now in the process of deleting xD Thanks anyway :) – niall watson Feb 6 '15 at 2:30

Use that command:

awk '$2=="python"{print}' a.txt | sort -dk3

If the second field is python print the whole line and let it sort on the 3rd field.


If you are not familiar with awk you might find following solution easier to grasp:

grep "python" a.txt | sort -dk 3 | cut -d " " -f 1,3
  • grep selects lines that contain given word

  • sort is sorting in descending order based on third key

  • cut is getting rid of the 'python' word. If it is showing in every line, it does not bring any information into the picture.


Ben C
Gerry E
Jamie E
Steven E
Phil F

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.