sorting - Sort paragraphs in text file from bash -


the sort utility let's conveniently sort lines in file. however, there elegant way sort blank-line separated paragraphs in bash?

for example

ccc aa  aba bbb  aba ccc  aaa 

would have become

aaa  aba bbb  aba ccc  ccc aa 

one solution seems to replace new line symbol on non-blank lines:

ccc\naa     aba\nbbb aba\nccc aaa 

then call run sort

aaa aba\nbbb aba\nccc ccc\naa     

and restore new lines:

aaa  aba bbb  aba ccc  ccc aa     

perl rescue;

perl -n00 -e 'push @a, $_; end { print sort @a }' file 

the -00 option enables "paragraph mode" splits input on empty lines.

if - in sample - last input line isn't empty, need add newline separately.

perl -n00 -e 'push @a, $_;    end { $a[-1] .= "\n" if $a[-1] !~ /\n\n$/;         print sort @a }' file