Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a text file containing one record per line which I'd like to sort alphabetically, except that I want '-' to sort after '[' and ']'. (The natural sort order has '-' before the square brackets.) Is there a way to modify the collation that sort(1) uses in order to achieve this?

share|improve this question
up vote 1 down vote accepted

One way would be to substitute a character that doesn't appear in your data, but sorts after the brackets (in some locale).

sed 's/-/|/g' inputfile | LC_ALL=C sort | sed 's/|/-/g' > outputfile

This is obviously not an ideal solution.

share|improve this answer
Yeah, I should have thought of that. Thanks. – uckelman Jan 1 '11 at 17:13

You will probably want to apply one of the suggested workarounds, but the answer to your question is no(t easily). If you want to change how sort sorts, and none of the special sort orders offered by the command-line options suit you, you will need to define your own locale. See localedef.

share|improve this answer

You could do it with perl:

perl -e 'print sort { (($a =~ /^-/ && $b =~ /^[\[\]]/) || ($a =~ /^[\[\]]/ && $b =~ /^-/)) ? ($b cmp $a) : ($a cmp $b) } (<>)' <filename>
share|improve this answer
a good example of executable line noise :-) – Javier Dec 30 '10 at 19:01

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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