次の入力テキストファイルを考えてみましょう。
some text …
% BEGIN
blabla
foo bar
blabla
blabla
% END
some text …
そしてfoobar.txt
次のファイル:
2 3
8 9
1 2
sed
(おそらく?)を使用してawk
この出力テキストファイルを取得する最も簡単な方法は何ですか?
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 …
ベストアンサー1
これは以下を使用する純粋なawkアプローチです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
GNU awkを使用すると、一時的に交換できます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
テスト:
$ 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 …