awk only solution (tested with gawk):
$ awk ' BEGIN { footer = ""; wl = ""; } END { while(( getline line < "sol.txt") > 0 ) { print(line) } footer = wl footer print substr(footer, 0, length(footer)-1); } # Blank line or comment-only (/^[[:blank:]]*#]]*$/ ||{ if (footer) { footer = wl footer print substr(footer, 0, length(footer)-1); footer = "" } wl = $0 "\n" } # Comment only /^[[:blank:]]*$]]*#/) { footer = footer $0 "\n"; } # Configuration line /^[[:blank:]]*[^[:space:]#]/ { print(wl footer $0); wl = ""; footer = ""; } ' < universe.txt > universe2.txt Producing:
# Universe configuration # pi = 3 # A good # e = mc**2 # To within a hair [cut 200 trillion lines] sol { mass = 42, start = 9.2 } # # END # With one line diff:
sh$ diff universe*.txt 8d7 < sol { mass = 42, start = 9.2 }