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
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.
In Excel, you can sort your table by one or more columns, by ascending or descending order, or do a custom sort.
-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.
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
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