AWK:ソース用語の後にターゲット単語を挿入する簡単な方法

AWK:ソース用語の後にターゲット単語を挿入する簡単な方法

私はawkに慣れていません。 198,058行の任意の行で、ソース用語の後に単一のターゲット用語を挿入するために、ここにこのコードがあります。

awk -i inplace '(NR==FNR){a[$1];next}
    (FNR in a) && gsub(/\<Source Term\>/,"& Target Term")
     1
    ' <(shuf -n 198058 -i 1-$(wc -l < file)) file

file次の文が含まれています。

David has to eat his vegetables .
This weather is very cold .
Can you please stop this music ? This is terrible music .
The teddy bear is very plushy .
I must be going !

たとえば、「wetter」という単語を「weather」の後に挿入したい場合、特定の行は次のようになります。

This weather Wetter is very cold .

ソース用語とターゲット用語のリストを含む2つの異なるファイルのみを含むようにコードをどのように書き換えますか?

ソース用語ファイルの名前が指定され、ターゲットsourceterms用語ファイルの名前が仮定されますtargetterms

sourcetermsこれらの用語を含むリストがある場合

vegetables
weather
terrible
plushy
going

targetterms次の用語を含めてください。

Gemüse
Wetter
schreckliche
flauschig
gehen

コード内のfile各行にソース用語が含まれていることを確認し、その後にターゲット用語を挿入することで、コードは次のようになりますfile

David has to eat his vegetables Gemüse .
This weather Wetter is very cold .
Can you please stop this music ? This is terrible schreckliche music .
The teddy bear is very plushy flauschig.
I must be going gehen!

上記のコードを書き直すことはできますか?

ベストアンサー1

ARGINDとワード境界にはGNU awk(OPが使用する)を使用します。

$ cat tst.awk
ARGIND == 1 { olds[FNR] = "\\<" $1 "\\>"; next }
ARGIND == 2 { map[olds[FNR]] = "& " $1; next }
{
    for ( old in map ) {
        new = map[old]
        gsub(old,new)
    }
    print
}

$ awk -f tst.awk sourceterms targetterms file
David has to eat his vegetables Gemüse .
This weather Wetter is very cold .
Can you please stop this music ? This is terrible schreckliche music .
The teddy bear is very plushy flauschig .
I must be going gehen !

上記では、ソースに正規表現メタ文字が含まれておらず、代替テキストに&逆参照メタ文字が含まれていないとします。また、同じ単語がソースとターゲットの両方に現れる場合、置換がどの順序で発生するかは関係ありません。

おすすめ記事