Using AWK to find top Nth values in Nth column

I have an awk script to find the maximum value of the 2nd column of a 2 column datafile, but I need to find the top 5 maximum values of the 2nd column.

Here is the script that works for the maximum value.

awk 'BEGIN { subjectmax=$1 ;  max=0} $2 >= max {subjectmax=$1 ; max=$2} END {print ""subjectmax" "max""}' filename

The data file contains the format of -
0001 1
0002 2
0003 3
0004 4
0005 5
0006 6

So the output would be
0006 6

I am looking for an output of
0006 6
0005 5
0004 4
0003 3
0002 2

Thanks

awk '{print $2, $1}' datafile | sort -rn | head -n 5

hope this might help you:

cat <filename> | sort -rn | head -5

That is a useless use of cat, and won't work since you're not sorting on the right column.

Perhaps awk isn't needed though, just

sort -rn -k 2 < filename | head -n 5
1 Like