I've seen many variations of this question on stack overflow/exchange, but none of them seem to address exactly what I'm looking for.
I have a file that looks like this:
bla
bla
bla
tag
text 1
text 2
tag
bla
bla
I have a variable (call it X) that contains
alpha
beta
gamma
I'm looking for an awk (or sed) expression that removes the text between the two "tag" lines and replaces it with the contents of variable X. The end result should be:
bla
bla
bla
tag
alpha
beta
gamma
tag
bla
bla
I think I need to do something like this:
awk -v var="$X" 'BEGIN{RS=""; FS="\n"} /tag/ {print var; next} {print $0"\n"}'
but this deletes the tags and injects two copies of $X
Here's one approach.
awk -v var="$X" '/tag/ && !p {
print; print var; p=1; next}
/tag/ {p=0} !p'
This removes the pesky manipulations of Awk's internal variables, and instead uses a simple state variable p
which is true in the range when you don't want to simply print the current line. The first time you see tag
, print the variable also, and set p
to 1. The next time, turn off p
again.