How to do custom sorting using unix sort?
Posted
by
jewelia
on Super User
See other posts from Super User
or by jewelia
Published on 2012-10-17T17:23:22Z
Indexed on
2012/10/18
5:09 UTC
Read the original article
Hit count: 479
I'm using unix sort to sort a comma delimited file with multiple columns. Thus far, this has worked perfectly for sorting the data either numerically or in alphabetical order:
Example file before any sorting:
C,United States,WA,Tacoma,f,1
A,United States,MA,Boston,f,0
B,United States,NY,New York,f,5
A,Canada,QC,Montreal,f,2
A,Bahamas,Bahamas,Nassau,f,2
A,United States,NY,New York,f,1
Sort the file: $ sort -t ',' -k 2,2 -k 3,3 -k 4,4 -k 5,5r -k 6,6nr tmp.csv
Sorted result:
A,Bahamas,Bahamas,Nassau,f,2
A,Canada,QC,Montreal,f,2
A,United States,MA,Boston,f,0
B,United States,NY,New York,f,5
A,United States,NY,New York,f,1
C,United States,WA,Tacoma,f,1
Here is the issue: I want to sort column 2 based on a custom sort, meaning I want United States first, then Canada, then Bahamas:
Desired sort:
A,United States,MA,Boston,f,0
B,United States,NY,New York,f,5
A,United States,NY,New York,f,1
C,United States,WA,Tacoma,f,1
A,Canada,QC,Montreal,f,2
A,Bahamas,Bahamas,Nassau,f,2
Is there some way to pass unix sort a custom sort order that it can then apply? Something like:
$ sort -t ',' -k 2,2:'United States, Canada, Bahamas' -k 3,3 -k 4,4 -k 5,5r -k 6,6nr tmp.csv
Thanks!
© Super User or respective owner