Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unix sort multiple fields

I'm trying to sort the file below as follows:

col1 (Ascending) col2 (Descending) col3 (Ascending) col4 (Descending)

I want to use the -k command, not the +- syntax. I've figured out how to use the old syntax:

sort -t " " +0 -1 +2 -3 +4r testfile

but it's hardly intuitive. I haven't figured out the right way to use the -k option. Thank you.

Here's the testfile:

5 3 2 9
3 4 1 7
5 2 3 1
6 1 3 6
1 2 4 5
3 1 2 3
5 2 2 3

Result:

1 2 4 5
3 4 1 7
3 1 2 3
5 3 2 9
5 2 2 3
5 2 3 1
6 1 3 6
like image 876
WLinden Avatar asked Jun 14 '11 01:06

WLinden


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.

Is it possible to sort by multiple columns?

In Excel, you can sort your table by one or more columns, by ascending or descending order, or do a custom sort.

How do you sort a third column in Unix?

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


1 Answers

You need one of:

sort --key=1,1 --key=2,2r --key=3,3 --key=4,4r
sort -k1,1 -k2,2r -k3,3 -k4,4r

as in the following transcript:

pax$ echo '5 3 2 9
3 4 1 7
5 2 3 1
6 1 3 6
1 2 4 5
3 1 2 3
5 2 2 3' | sort --key=1,1 --key=2,2r --key=3,3 --key=4,4r

1 2 4 5
3 4 1 7
3 1 2 3
5 3 2 9
5 2 2 3
5 2 3 1
6 1 3 6

Remember to provide the -n option if you want them treated as proper numbers (variable length), such as:

sort -n -k1,1 -k2,2r -k3,3 -k4,4r
like image 56
paxdiablo Avatar answered Sep 17 '22 13:09

paxdiablo