Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort by third column leaving first and second column intact in Linux?

Tags:

I need to sort a flat file by third column leaving first column intact [First column is already sorted] (in linux). (second column may change)

Example i/p file:-

b:di:wave
b:di12:red
b:di12:wave
b:di06:pir

Should look like:-

b:di06:pir
b:di12:red
b:di12:wave
bast:di:wave

I tried several sorting options but I could sort only by second column but not third.

Can someone please help ?

like image 813
user1429246 Avatar asked Jun 12 '12 23:06

user1429246


People also ask

How do I sort the third column in Linux?

No, by default sort columns are blank separated, they are not character columns, to sort on the 3rd character column, the syntax would be: sort -k 1.3,1.3 .

How do I sort a column according to Linux?

5. -k Option: Unix provides the feature of sorting a table on the basis of any column number by using -k option. Use the -k option to sort on a certain column. For example, use “-k 2” to sort on the second column.

How do I sort by second column in Linux?

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

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.


1 Answers

Try this:

sort  -t: -k1,1 -k3 data.txt

gives:

bast:disp-san-d5-06:piranha 
bast:display-san-12:redbird
bast:display-san-07:waverider
bast:display-san-12:waverider

This will sort with the 1st field as primary key, and the 3rd field as secondary key splitting the line into fields by :

Details:

data.txt contains the 4 lines from your post.

You can specify multiple fields as sorting keys, see the man page

-k1,1 means sort on the first field (start at field 1 and end at field 1, otherwise it would continue using the rest of the line for determining the sort)

-k3 means sort on the 3rd field as secondary key. Since there are no other fields behind it is not necessary to specify -k3,3 but it wouldn't hurt either.

-t: means delimit fields in lines with the : character, otherwise blank is used by default

More information see this SO question Sorting multiple keys with Unix sort and the sort man page

like image 168
Levon Avatar answered Sep 17 '22 18:09

Levon