rmazurki
rmazurki

Reputation: 11

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?

Upvotes: 0

Views: 67

Answers (1)

Ray Butterworth
Ray Butterworth

Reputation: 618

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

Upvotes: 2

Related Questions