Unix sort command with columns

I’ve written about how to count unique occurrences of a string in a file in unix but today I needed to push the unix sort command a little further.

Consider the case where you have a CSV file with a column of text and a column of numbers like the following:

s, 3
h, 6
a, 4
c, 3
z, 2
b, 4

How would you sort it numerically by column two and then by column one such that if there are multiple numerical values in column two with the same value then column one will be sorted alphabetically? Well, of course the sort command has everything you need:

[~]$ sort -k2n -k1 -t',' /file
z, 2
c, 3
s, 3
a, 4
b, 4
h, 6

Breaking this down:

  • -kX – refers to column number so k2 is the second column
  • n – sorts numerically instead of alphabetically
  • -t – delimits by comma instead of whitespace

Finally, the ordering of the columns in the command dictates which column to order by first.

Short URL: http://goo.gl/QY7iR

Leave a Reply

Your email address will not be published. Required fields are marked *