Awk - delete a line if the following lines do not match the pattern
I would like to solve the following problem and so far I think awk might be right too, but please confirm if I am wrong.
I have console output that follows this pattern:
HEADER: HeaderInfo1
Details 1
Details 2
HEADER: HeaderInfo2
HEADER: HeaderInfo3
Details 3
Details 4
HEADER: HeaderInfo4
I would like to convert this to the following:
HeaderInfo1: Details 1
HeaderInfo1: Details 2
HeaderInfo3: Details 3
HeaderInfo3: Details 4
So, as you can see, every detail belongs to the nearest title. Number of details in a variable header Empty headers should be ignored.
I've tried all sorts of regex and sed magic, but this is similar to the awk case I guess. However, I don't quite know where to start.
source to share
Assuming your information is in a file named info
:
$ awk '/^HEADER/{hdr=$2;next} {print hdr": "$0}' info
HeaderInfo1: Details 1
HeaderInfo1: Details 2
HeaderInfo3: Details 3
HeaderInfo3: Details 4
Explanation
The program awk
is divided into two parts:
-
/^HEADER/{hdr=$2;next}
For lines starting with
HEADER
, the second field is stored in a variablehdr
and thenawk
instructed to move to the next line. -
{print hdr": "$0}
For all other lines, the last header value is printed
hdr
, followed by a colon, followed by a line ($0
).
source to share