Using awk and sorting

Viewed 4297

I have a file that contains names and numbers like so:

students.txt:

Student A F 40 50 60
Student B F 50 60 70
Student C M 60 70 80
Student D M 100 90 90
Student E F 80 90 100
Student F M 20 30 40
Student G M 30 40 50

I want to sort these names using awk, and sort by the last number on a line.

When I try

sort -k6 students.txt | awk '{print}'

The output that is given to me is

... 100
... 40
... 50
... 60
... 70
... 80
... 90

As a result, it is mostly sorted except the first one. Is there a reason why 100 is at the start of the output rather than at the end?

1 Answers

You need to use numeric sort, via the -n flag. From the sort(1) man page:

   -n, --numeric-sort
          compare according to string numerical value

Result:

$ sort -n -k6 students.txt
Student F M 20 30 40
Student G M 30 40 50
Student A F 40 50 60
Student B F 50 60 70
Student C M 60 70 80
Student D M 100 90 90
Student E F 80 90 100
Related