shell sort command : How to sort by the last colum

2019-09-21 01:24发布

问题:

If the data is like the follow:

a,b,3
c,d,e,f,2
g,1

I want sort by the last column. the result should be:

g,1
c,d,e,f,2
a,b,3

回答1:

if the last field is single digit

$ rev file | sort | rev

you may need to add -t, -n to sort for numerical ordering but single digits it doesn't matter.

or, for the general case with awk

$ awk -F, '{a[$NF]=$0} END{n=asorti(a,d); for(k=1;k<=n;k++) print a[d[k]]}' file

g,1
c,d,e,f,2
a,b,3

This will fail if the last field is not unique. Using decorate/sort/undecorate idiom you can write instead (as you found yourself)

$ awk -F, '{print $NF FS $0}' file | sort -n | cut -d, -f2-

it's safer to use the field delimiter between the key and the record since you want to ensure the FS doesn't appear in the key itself.



回答2:

I have a stupid but simple way to do it :)

// if original data in the file : ~/Desktop/1.log

$ awk -F, '{print $NF, $0}' ~/Desktop/1.log | sort -n | awk '{print $2}'

g,1

c,d,e,f,2

a,b,3