How to numerical sort by last column?

All we need is an easy explanation of the problem, so here it is.

I have this input:

sdkxyosl 1
safkls 2
asdf--asdfasxy_asd 5
dkd8k  jasd 29
sdi44sw 43
asasd afsdfs 10
rklyasd 4

I need this output:

sdi44sw 43
dkd8k  jasd 29
asasd afsdfs 10
asdf--asdfasxy_asd 5
rklyasd 4
safkls 2
sdkxyosl 1

So i need to sort the lines by the last column.

I don’t know how many columns are in one line.

I just can’t figure it out, how to do it. I don’t have “perl powers”. I just have ~average scripting powers with sed, awk, cut, etc..

Does somebody know how to do it?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

The following command line uses awk to prepend the last field of each line of file.txt, does a reverse numerical sort, then uses cut to remove the added field:

awk '{print $NF,$0}' file.txt | sort -nr | cut -f2- -d' '

Method 2

Sort last column numerically descending with GNU awk:

awk '{
       # save current row in array with current row number as index
       row[NR]=$0

       # save current last field in array with current row number as index
       last[NR]=$NF
     }
     END{
       # sort array "last" numerically ("num") based on its
       # values ("val") descending ("desc")
       PROCINFO["sorted_in"]="@val_num_desc";

       for(i in last)
         print row[i]
     }' file

As one line:

awk '{ row[NR]=$0; last[NR]=$NF } END{ PROCINFO["sorted_in"]="@val_num_desc"; for(i in last) print row[i] }' file

Output:

hello my name is Jordan: 476 
hello my name is Manu: 98
hello my name is Joi: 45
hello my name is Loi:  23 
hello my name is John:  4

See 8.1.6 Using Predefined Array Scanning Orders with gawk for more sorting algorithms and 8 Powerful Awk Built-in Variables – FS, OFS, RS, ORS, NR, NF, FILENAME, FNR

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply