Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unix: sort by last number of line

Tags:

unix

How do you sort a file by the last number in a line?

Assuming the last character of every line is a number. INPUT:

facebook.com/pageA,2,11,11
facebook.com/pageB,0,0,20
facebook.com/pageC,0,0,6
facebook.com/pageD,1,22,239

Desired Output:

facebook.com/pageC,0,0,6
facebook.com/pageA,2,11,11
facebook.com/pageB,0,0,20
facebook.com/pageD,1,22,239

Help??

like image 669
user1899415 Avatar asked Jun 14 '13 02:06

user1899415


3 Answers

You can use sort.

sort -n -t, -k4 INPUT
like image 112
falsetru Avatar answered Nov 15 '22 11:11

falsetru


If your input file has different columns in each line then you can make the last column as first column, sort by it and then remove it.

awk '{print($NF,$0)}' FS=, OFS=, inputFile | sort -t, -nk1 | cut -f2- -d,
like image 45
jaypal singh Avatar answered Nov 15 '22 11:11

jaypal singh


Use rev to reverse each line, then sort, then re-reverse:

rev < $file | sort | rev
like image 36
Adam Liss Avatar answered Nov 15 '22 11:11

Adam Liss