Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preserve original order if numeric value is equal in coreutils sort?

Consider this snippet:

echo '7 a
3 c
3 b
2 first
2 second
2 third
2 fourth
2 fifth
9 d
2 sixth
' | sort -n -k 1

It gives an output of:

2 fifth
2 first
2 fourth
2 second
2 sixth
2 third
3 b
3 c
7 a
9 d

While the list is correctly ordered numerically keyed by first character, also for those values which are contiguous and equal, the original order has been shuffled. I would like to obtain:

2 first
2 second
2 third
2 fourth
2 fifth
2 sixth
3 c
3 b
7 a
9 d

Is this possible to do with sort? If not, what would be the easiest way to achieve this kind of sorting using shell tools?

like image 979
sdaau Avatar asked Sep 01 '25 01:09

sdaau


2 Answers

Just add the -s (stable sort) flag, this disables last-resort comparison

echo '7 a
3 c
3 b
2 first
2 second
2 third
2 fourth
2 fifth
9 d
2 sixth
' | sort  -k 1,1n -s

2 first
2 second
2 third
2 fourth
2 fifth
2 sixth
3 c
3 b
7 a
9 d
like image 76
iruvar Avatar answered Sep 02 '25 16:09

iruvar


Add line numbers with nl, pipe to sort -k2,1 to use the line numbers as the secondary key, then cut the numbers off with cut. Or use sort -s. :p

like image 31
Amadan Avatar answered Sep 02 '25 16:09

Amadan