Home > Software design >  Sort a text file by numeric value of the last word on each line
Sort a text file by numeric value of the last word on each line

Time:11-22

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)

CodePudding user response:

You can use the "decorate-sort-undecorate" pattern here:

awk '{print $NF "\t" $0}' file.txt | sort -nr -k1,1 | cut -f 2-

CodePudding user response:

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
  •  Tags:  
  • bash
  • Related