Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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

3 Answers 3

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
2  
a good example of executable line noise :-) –  Javier Dec 30 '10 at 19:01

Your Answer

 
discard

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.