Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

unix

sorting

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?

like image 359
jake9115 Avatar asked Aug 12 '13 17:08

jake9115


People also ask

How do I sort multiple columns in Unix?

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.

How do you sort by second field in Unix?

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.).

What command should I use to arrange the entries of a file alphabetically reverse order numerical order?

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).

Which command is used to arrange lines alphabetically or numerically?

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.


2 Answers

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.
like image 68
Rahul Tripathi Avatar answered Sep 28 '22 20:09

Rahul Tripathi


This should work:

sort -t "," -k1,1 -k2n,2 file
like image 21
jenish Avatar answered Sep 28 '22 20:09

jenish