Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort paragraphs in text file from bash

Tags:

bash

sorting

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    
like image 288
john1234 Avatar asked Jun 07 '16 01:06

john1234


1 Answers

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
like image 84
tripleee Avatar answered Oct 08 '22 00:10

tripleee