jake9115
jake9115

Reputation: 4084

How to sort a file in unix both alphabetically and numerically on different fields?

Please don't think this is a repeat of the "Sorting alphanumeric data in unix" question... I looked at the other answers, and think my case is a bit different!

I have data like this:

A    192
D    112
D    188
C    091
A    281
B    919

...And I want to sort first column 1 (alphabetically), and then by column 2 (numerically). I tried using:

sort -n -k1,2

...But this gave me correctly sorted for the first field, but then the wrong sorting for the second field (1000,1002,1003,10,1 ... instead of 1,10,1000,1002,1003).

Can someone please suggest how to sort these two columns the way I'd like?

Upvotes: 36

Views: 98076

Answers (2)

jenish
jenish

Reputation: 71

This should work:

sort -t "," -k1,1 -k2n,2 file

Upvotes: 7

Rahul Tripathi
Rahul Tripathi

Reputation: 172418

Try using like this:-

sort -k1,1 -k4,4n
  • -n : Makes the program sort according to numerical value
  • -k opts: Sort data / fields using the given column number. For example, the option -k 2 made the program sort using the second
    column of data. The option -k 3,3n -k 4,4n sorts each column. First
    it will sort 3rd column and then 4th column.

Upvotes: 45

Related Questions