3

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?

0

2 Answers 2

8

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

2
  • Or just LC_ALL=C sort x.
    – Kusalananda
    Jun 29, 2018 at 18:20
  • @Kusalananda Thanks, I've edited that into the answer.
    – kubanczyk
    Jun 29, 2018 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.

1
  • 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, 2015 at 17:50

Not the answer you're looking for? Browse other questions tagged .