When I sort foo and foo1, I expect foo to come first, which is what happens ordinarily with unix sort.

$ echo -e "foo1\nfoo" | sort

But when I add and underscore and use the -t and -k options, it doesn't produce the same sort order.

$ echo -e "foo1_3\nfoo_3" | sort -t_ -k1

What is the correct set of options to use to make foo_3 come before foo1_3? I have LC_COLLATE=C and am on Ubuntu 14.04.



echo -e "foo1_3\nfoo_3" | sort -t_ -k1,1

As the sort manual states:

`-k POS1[,POS2]' `--key=POS1[,POS2]'
    Specify a sort field that consists of the part of the line between
    POS1 and POS2 (or the end of the line, if POS2 is omitted),
  • PS: I never knew this and was always puzzled by sort -k's behaviour, untill this question triggered me to find out what was going on. So thanks a lot for asking! – reinierpost Sep 25 '15 at 8:15

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.