How can I make unix sort work properly using the underscore as a field separator?

2

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
foo
foo1

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
foo1_3
foo_3

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.

rmccloskey

Posted 2015-09-24T17:27:20.430

Reputation: 123

Answers

1

Use

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),
    _inclusive_.

reinierpost

Posted 2015-09-24T17:27:20.430

Reputation: 1 904

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 – 2015-09-25T08:15:42.107