15

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
1
  • Your "Result" data doesn't match the output of your old syntax example. Commented Jun 14, 2011 at 1:39

2 Answers 2

29

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.