9

I have a file which contains already ordered data and I'd like to re-order the file according to the values in one key, without destroying the order of the data in the other keys.

How do I prevent GNU sort from performing row sorting based on the values of keys I have not specified, or how do I specify to GNU sort to ignore a range of keys when sorting?

File data.txt:

1 Don't
2 C 
1 Sort
2 B
1 Me
2 A

Expected output:

1 Don't
1 Sort
1 Me
2 C
2 B
2 A

Command:

sort -k 1,1 <data.txt

Result: unwanted sorting I didn't ask for:

1 Don't
1 Me
1 Sort
2 A
2 B
2 C
20

You need a stable sort. From man sort:

-s, --stable
       stabilize sort by disabling last-resort comparison

viz.:

$ sort -sk 1,1 <data.txt
1 Don't
1 Sort
1 Me
2 C 
2 B
2 A

Note that you probably also want a -n or --numeric-sort if your key is numeric (for example, you may get unexpected results when comparing 10 to 2 with the default - lexical - sort order). In which case it's just a matter of doing:

sort -sn <data.txt

No need to extract the first field as the numeric interpretation of the whole line will be the same as the one of the first field.

4

For (non-GNU) sort implementations that lack a -s option, you can always do:

<data.txt awk '{print NR "\t" $0}' | sort -n -k 2,2 -k 1,1 | cut -f 2-

That is, prepend the line number to make it the second sort key, and strip it afterwards.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.