Here's a pure awk way to do it, using getline
:
awk '
/% BEGIN/ {
s = 1;
}
s == 1 {
b = b == "" ? $0 : b ORS $0
}
/% END/ {
while ((getline repl < "foobar.txt") > 0) {
tmp = b;
sub(/foo bar/, repl, tmp);
print tmp;
}
b = "";
s = 0;
next;
}
s == 0 {
print;
}' input
With GNU awk, you can make the substitution without a temporary - using gensub
:
gawk '
/% BEGIN/ {
s = 1;
}
s == 1 {
b = b == "" ? $0 : b ORS $0
}
/% END/ {
while ((getline repl < "foobar.txt") > 0) {
print gensub(/foo bar/, repl, 1, b);
}
b = "";
s = 0;
next;
}
s == 0 {
print;
}' input
Testing:
$ gawk '
> /% BEGIN/ {s = 1;}
> s == 1 {b = b == "" ? $0 : b ORS $0}
> /% END/ {while ((getline repl < "foobar.txt") > 0) {print gensub(/foo bar/, repl, 1, b);} s = 0; next;}
> s == 0 {print}' input
some text …
% BEGIN
blabla
2 3
blabla
blabla
% END
% BEGIN
blabla
8 9
blabla
blabla
% END
% BEGIN
blabla
1 2
blabla
blabla
% END
some text …
%BEGIN...%END
block, and that block must be duplicated as many times asfoobar.txt
has values (with the replacement offoo bar
changing for each copy)? And the text outside that%BEGIN...%END
block must be left as-is? – ilkkachu May 13 '17 at 22:13