Strange behaviour of redhat linux sort


Redhat linux, file to sort - "aaa":
4;AAA;456
3;BBB;567
2;AAA;123
1;BBB;234
5;AAA;000

sort only by second field - command:
sort -t ";" -k2,2 aaa

output is:
2;AAA;123
4;AAA;456
5;AAA;000
1;BBB;234
3;BBB;567

In my opinion output should be:
4;AAA;456
2;AAA;123
5;AAA;000
3;BBB;567
1;BBB;234

Error in sort?

- - Source

Answers

answered 1 week ago Ray Butterworth #1

There could be other reasons, but I'll guess that it is your "opinion", because you think that for records with equal keys, whichever one was first encountered in the file should be first in the output.

That is known as a "stable sort".

Stable sorts can take more work, and in most cases aren't required, so by default the sort command doesn't do it. Hence the results you saw.

It can do it if you want it to though:

$ sort --stable --field-separator=";" --key="2,2" aaa
4;AAA;456
2;AAA;123
5;AAA;000
3;BBB;567
1;BBB;234

comments powered by Disqus