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?

link|improve this question
feedback

3 Answers

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.

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

You could do it with perl:

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

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.

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

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