Grouped sorting of continuous paragraphs (separated by blank line)

sorttext processing

I think I'm pretty experienced now in sorting by columns; however, I haven't found anything so far how to sort continuous rows.

Supposing we have a text file that looks like this: (very simplified, of course)

Echo
Alpha
Delta
Charlie

Golf
Bravo
Hotel
Foxtrot

Now, is it possible to sort the lines alphanumerically per each block separately?
I mean, so that the result looks like this:

Alpha
Charlie
Delta
Echo

Bravo
Foxtrot
Golf
Hotel

Telling from what I found in the sort man page, this might not be possible with the built-in UNIX sortcommand. Or can it even be done without having to resort to external/third-party tools?

Best Answer

Drav's awk solution is good, but that means running one sort command per paragraph. To avoid that, you could do:

< file awk -v n=0 '!NF{n++};{print n,$0}' | sort -k1n -k2 | cut -d' ' -f2-

Or you could do the whole thing in perl:

perl -ne 'if (/\S/){push@l,$_}else{print sort@l if@l;@l=();print}
          END{print sort @l if @l}' < file

Note that above, separators are blank lines (for the awk one, lines with only space or tab characters, for the perl one, any horizontal or vertical spacing character) instead of empty lines. If you do want empty lines, you can replace !NF with !length or $0=="", and /\S/ with /./.

Related Question