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?
Sorting by multiple columns is similar to sorting by a single column. To sort on a range of columns, simply specify the start and end columns in the column range to use for sorting.
Use the -k option to sort on a certain column. For example, use " -k 2 " to sort on the second column. In old versions of sort, the +1 option made the program sort on the second column of data ( +2 for the third, etc.).
The sort command sorts the contents of a file, in numeric or alphabetic order, and prints the results to standard output (usually the terminal screen).
The sort command arranges data alphabetically or numerically in ascending or descending order. The grep command displays or hides only the required information you want.
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.
This should work:
sort -t "," -k1,1 -k2n,2 file
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With