2

I have a file foo whose contents are

140,22
236,224
2,86

If I sort it with sort foo I get the same result. This tells me that , comes after numbers, or at the very least that , comes after 3.

Paradoxically, the following happens:

$echo -e "2\n,\n3" | sort
,
2
3

Which tells me that , comes before 2. I don't get it. Can someone please explain?

3

Sort order depends on your locale, so there's probably some odd interpretation going on there. I get the same results as you on my system. Here, a comma is ignored by the locale. Hence, if we add 276 and 296 to your list:

$ sort /tmp/tosort
140,22
236,224
276
2,86
296

This also explains the results from your second command. The comma isn't being sorted first, but being ignored. Hence, it's essentially sorting a empty string. If you add a literal empty string to your test, you'll also see it at the beginning.

$ echo -e "2\n,\n3\n" | sort

,
2
3

(It's unclear to me why the empty string precedes the comma. I suspect that the comma is used when there is a tie.)

You will get more predictable results using a "standard" POSIX locale.

$ export LC_ALL=C
$ sort foo
140,22
2,86
236,224
  • I want to sort lexicographically. The two bottom rows tie on the first character and the second one compares 3 to , and places 3 before the comma. – Can't Sort This Jun 16 at 23:00
  • I don't get how locale can account for inconsistencies in sorting with the same locale. – Can't Sort This Jun 16 at 23:12
  • Thanks for the effort, Sparhawk. The example doesn't help me. echo -e "9\n," | sort does place the comma before 9, which very odd, but at least it is consistent. I still don't get why it behaves the way it does. It's the same locale for both sorts. – Can't Sort This Jun 16 at 23:19
  • @Can'tSortThis No worries. Edited again – Sparhawk Jun 16 at 23:24
  • Got it! Thanks. – Can't Sort This Jun 16 at 23:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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