GNU Sort – Sort by Single Key and Prevent Unwanted Sorting

sort

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

Best Answer

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.

Related Question