The READIN Family Album
Me and a lorikeet (February 24, 2008)

READIN

Jeremy's journal

Disbelief is more resistant than faith because it is sustained by the senses.

Gabriel García Márquez


(This is a page from my archives)
Front page
More recent posts
Older posts

Archives index
Subscribe to RSS

This page renders best in Firefox (or Safari, or Chrome)

🦋 Sorting on multiple keys

Searched around for a while on Friday trying to figure out how to invoke the UNIX sort command with multiple keys. I eventually found what I was looking for but now can't figure out where I read it. I will make a note of it here as it seems to be pretty difficult to find -- it took me about an hour of Googling to come up with it.

Each key you want should be specified as a separate parameter to sort, in the desired sort order. Each can have its own sort order specified. So

sort -k 1,1 -k 2,2n
sorts on the first column, then the second; the second column is sorted in numeric order. (This is incidentally the behavior I was looking for.)
sort -k 2,2r -k 3,3
sorts the second column in reverse order, then the third column. Etc. It looks like there are other syntactic ways of specifying the same behavior; but this one definitely works. (At least with sort in Cygwin and I'm assuming in other non-Cygwin Linuxes.)

Note that I'm using "column" in this post to mean "whitespace-delimited field" -- i.e. if you (say) imported the text file to be sorted into Excel, each field would take up one column. There are also parameters to sort that let you specify the field delimiter. Also the -k parameter allows you to specify that the key is made up of multiple fields or of substrings of a field or fields. I did not use any of this and would recommend you examine the man page before you use it.

posted afternoon of Monday, April 25th, 2005

Respond:

Name:
E-mail:
(will not be displayed)
Link:
Remember info

Drop me a line! or, sign my Guestbook.
    •
Check out Ellen's writing at Patch.com.

Where to go from here...

Friends and Family
Programming
Texts
Music
Woodworking
Comix
Blogs
South Orange
readinsinglepost