The sort
utility let's you conveniently sort lines in a file. However, is there an elegant way to sort blank-line separated paragraphs in bash?
For example
ccc
aa
aba
bbb
aba
ccc
aaa
would have to become
aaa
aba
bbb
aba
ccc
ccc
aa
One solution seems to be to replace new line symbol on all non-blank lines:
ccc\naa
aba\nbbb
aba\nccc
aaa
then call run sort
aaa
aba\nbbb
aba\nccc
ccc\naa
and then restore new lines:
aaa
aba
bbb
aba
ccc
ccc
aa
Perl to the rescue;
perl -n00 -e 'push @a, $_; END { print sort @a }' file
The -00
option enables "paragraph mode" which splits input on empty lines.
If - as in your sample - the last input line isn't necessarily empty, you will need to add a newline separately.
perl -n00 -e 'push @a, $_;
END { $a[-1] .= "\n" if $a[-1] !~ /\n\n$/;
print sort @a }' file
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With