Sort file by group of lines
Using Perl you could run something along the lines of:
- slurp the file (
perl -0n
) - split the input by not indented lines
split(/^(?=\S)/m)
- sort and print
perl -0ne 'print sort split(/^(?=\S)/m) ' ex
First sed puts each section on a single line, using the text <EOL>
as delimiter between section lines. Then I'm sorting the sections and using the second sed to revert each <EOL>
back to a newline.
sed -r ':r;$!{N;br};s:\n([[:blank:]])(\1*):<EOL>\1\2:g' file|sort|sed -r '/^$/d;:l;G;s:(.*)<EOL>(.*)(\n):\1\3\2:;tl;$s:\n$::'
I didn't chose a character as a delimiter, since the input file might have it, so I used <EOL>
instead.
Output: I added a newline after each section, except the last, to recreate the style of the input file.
FirstSection
Unique first line in first section
Unique second line in first section
NthSection
Unique first line in Nth section
Unique second line in Nth section
SecondSection
Unique first line in second section
Unique second line in second section