Gawkの相互参照フィールドと値の挿入

Aug 25 2020

この相互参照スクリプトを拡張したいと思います。どんな助けでも大歓迎です。

現在のスクリプト>

gawk -F"\t" '
    FNR==NR{a[$1][$2]=1;next}
    $2 in a{for(i in a[$2]) print $1 FS i}
' a.txt b.txt

a.txtの例:

[email protected]    hello example
[email protected]    hello world

b.txtの例:

Charles    [email protected]
Erica    [email protected]

出力>

Charles    hello example
Charles    hello world
Erica    hello example
Erica    hello world

基本的にこのスクリプトチェックがかどうかを確認する$1にはa.txtに等しく、$2b.txtそうであれば、出力$2からa.txt並ん$1b.txt(上に見られるように)

ただし、別の形式を使用してb.txt直接編集したいのですが、望ましい結果の例>

a.txt 上記と同じままになります。

b.txtの例:

Charles    [email protected]    0    msg    example
Erica    [email protected]    0    msg    example

これでb.txt5つの列ができたので、前と同じように$2fromb.txtから$1from a.txtに一致しますが$2、a.txtからb.txtに挿入し$4て、現在の値を新しい値に置き換えます。

また、私はしたいignore-caseの一致に、私は、私はちょうどラップすることができますね$1,$2,etctolower()

必要な出力>

Charles    [email protected]    0    hello example    example
Erica    [email protected]    0    hello example    example

回答

2 Quasímodo Aug 25 2020 at 01:19

元のスクリプトを少し変更して、

awk '
    BEGIN{FS=OFS="\t"}
    #Parsing first file
    FNR==NR{a[tolower($1)]=$2;next}
    #Parsing second file
    {
        i=tolower($2) if(i in a){$4=a[i];print}
    }
' a.txt b.txt > c.txt &&
mv c.txt b.txt

tolowerの1番目のフィールドa.txtb.txt大文字と小文字を区別せずに2番目のフィールドと照合するために使用されます。

出力は一時ファイルに保存され、正常に終了しc.txtb.txt場合は上書きされますawk

1 EdMorton Aug 25 2020 at 05:17
awk '
    BEGIN { FS=OFS="\t" }
    { split(tolower($0),lc) } NR==FNR { a[lc[1]] = $2
        next
    }
    lc[2] in a {
        $4 = a[lc[2]]
        print
    }
' a.txt b.txt