Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

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)

like image 644
Tenko Avatar asked Jan 24 '23 05:01

Tenko


2 Answers

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

awk '{print $NF "\t" $0}' file.txt | sort -nr -k1,1 | cut -f 2-
like image 70
glenn jackman Avatar answered Jan 26 '23 17:01

glenn jackman


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
like image 31
HatLess Avatar answered Jan 26 '23 19:01

HatLess