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
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
What about sort -n -k 1n -k 2rn -k 3n -k 4rn
?
-k <FIELD><OPT1><OPT2>...
where OPT1 and OPt2 are simply sort
options, for example n
is numeric, r
is reverse
精彩评论