Sort a text file by numeric value of the last word on each line

Viewed 182

I have a file.txt with this text:

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

I want to order this file to echo it later and i want it to be like this:


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  

How can I do it? I know that ita can be done with sort -n but i need it the other way around and the problem is that it has text.. . Thanks (the numbers of the file are on different lines)

4 Answers

If you reverse the file, you can then sort from the numbers and reverse back

$ sed 's/[^0-9]*\(.*\)/\1 &/' input_file | sort -rn | sed 's/[^a-z]*\(.*\)/\1/'
blabla 45
blabla 23
blabla 12
blabla 5
blabla 4

sort has a "key" argument that lets you specify which "field" to sort on. I'm not sure this will work on all versions...in all shells...but it's great for one-offs when you just want the answer.

sort -n -k 6

You can do it with only one sort command:

sort -t : -n -r -k2 file.txt

this command segments each line by colon (-t :) and order by second field (-k2) in reverse mode (-r).

Related