3

This question already has an answer here:

I have 2 text files:

$ cat /tmp/test1
"AAP" bar
"AEM" bar
"AA" bar
"AEO" bar
"A" bar

$ cat /tmp/test2
"AEM" foo
"AAP" foo
"A" foo
"AEO" foo
"AA" foo

I want to sort them

$ sort /tmp/test1
"AA" bar
"AAP" bar
"A" bar              <-- "A" is in position 3
"AEM" bar
"AEO" bar

$ sort /tmp/test2
"AA" foo
"AAP" foo
"AEM" foo
"AEO" foo
"A" foo              <-- "A" is in position 5

Why does "A" end up in position 3 in /tmp/test1 and in position 5 in /tmp/test2?

My expectation is that each character per column will be compared.

As such, when comparing column 3, 'A', 'E' and '"' will be compared against each other, and this would be the ultimate determinant in the final sort order of this test data.

Clearly my expectation is wrong, so how does sort work, if not in the way I expected?

Is there command line option to sort or some other utility I can use to get the sort order I desire?

marked as duplicate by roaima, garethTheRed, vonbrand, G-Man, mdpc Nov 6 '15 at 1:15

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

7

You need to have collation locale changed. The behavior you describe is typical to en_US and many other locales. Fix with:

LC_ALL=C   sort  /tmp/test1

More in this answer: https://stackoverflow.com/questions/6531674/linux-sort-unexpected-output

  • Or just LC_ALL=C sort x. – Kusalananda Jun 29 '18 at 18:20
  • @Kusalananda Thanks, I've edited that into the answer. – kubanczyk Jun 29 '18 at 18:24
5

Possibly it only looks at alphabetical characters? Therefore, in the case of A the next alphabetical character is the b from bar.

  • 2
    I think you're right. From man sort: *** WARNING *** The locale specified by the environment affects sort order. Set LC_ALL=C to get the traditional sort order that uses native byte values. So possibly there is a locale specified that causes sort to behave like this. – Wildcard Nov 5 '15 at 17:50

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