awk '/^ABC/ && pre { print "END" dpre ORS $0; pre=""; n=0; next } { if(npre) print pre; n=1; pre=dpre=$0; sub(/[[:blank:]]+/," ", dpre) } END{ print "END" dpre }' infile
first block will be executed only if a line starts with ABC string and when a temporary variable pre was set otherwise next block will be executed.
the END{...} block will be executed only once and after end of all.
for the first line of course still pre variable doesn't set yet, so second block will be executed and it does following:
- if there was things inside
pre print it first if(pre) print pre (with this we delay printing of previous line in order to check if next line starts with ABC or not, because we need to add END in front of that line) - then we copy that line into say two separate variables
pre and dpre (one would be untouched (later we need print it untouched) and another we will update for formatting purposes and then print, so with sub(/[[:blank:]]+/," ", dpre) we replace all leading whitespaces (if any) in dpre into only 3 space characters to align formatting).
now we are at processing of the first line ABC, the variables value are as following:
pre=ABC dpre=ABC
then next line will be read i,e: 2 3 4;