How to numerical sort by last column?

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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

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


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

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x