Ubuntu – How to use sort on an awk print command

awkcommand linetext processing

I have a couple of commands in an awk script I'm writing:

print "Here are some players and their numbers, sorted by last name"
if(sum[x] > 500) {print x, $2}

Which outputs:

Here are some players and their numbers, sorted by last name
Lebron James 23
Kevin Durant 35
Kobe Bryant 24
Blake Griffin 32
Dikembe Mutumbo 55

How can I use the sort command in my awk script to sort the players and their numbers ONLY?

Best Answer

you can add | sort -k2 to your command. This will sort alphabetically based on the second column.

Example:

$ echo "Lebron James 23
Kevin Durant 35
Kobe Bryant 24
Blake Griffin 32
Dikembe Mutumbo 55" | sort -k2

results in

Kobe Bryant 24
Kevin Durant 35
Blake Griffin 32
Lebron James 23
Dikembe Mutumbo 55