5

Windowsで使用awkしています。というスクリプトがありますtest.awk。このスクリプトは、ファイルを読み取り、特定のフィールド (キー) を値に置き換える必要があります。key->value リストは、 というファイルにありますtranslate.txt

その構造は次のようになります。

e;Emil    
f;Friedrich
g;Gustaf
h;Heinrich
i;Ida

簡単な例では、私の入力ファイルは次のようになります

e,111    
f,222
g,333
h,444
i,555
..

したがって、出力は

Emil,111
Friedrich,222
Gustaf,333
Heinrich,444
Ida,555
..

私が持っているスクリプトは、ユーザー関数を使用して置換を行っていますが、この関数に別のファイルをソースとしてkey2value与えることに成功していません。translate.txt私のコードを見てください:

{   
    FS=","
    d=key2value($1)
    print d "," $2
}

function key2value(b)
{
    #this should use another file, not the currently processed one
    FILENAME="translate.txt"  

begin
{
    FS=";"

    if ($1=b)
    { 
       return $2
    }

end 

}

もう1つ、FSにはバグがあり、2行目からのみ機能します。

4

2 に答える 2

7

この単純なワンライナーでうまくいきます。

awk  'FNR==NR{a[$1]=$2;next}{print a[$1],$2}' FS=',|;' OFS=',' translate input
Emil,111
Friedrich,222
Gustaf,333
Heinrich,444
Ida,555

スクリプト形式:

BEGIN {                # The BEGIN block is executed before the files are read
    FS="[,;]"          # Set the FS to be either a comma or semi-colon
    OFS=","            # Set the OFS (output field separator) to be a comma
}
FNR==NR {              # FNR==NR only true when reading the first file
   key2value[$1]=$2;   # Create associative array of key,value pairs 
   next                # Grab the next line in the first file
} 
{                      # Now in the second file, print looked up value and $2 
    print key2value[$1],$2
}

次のように実行します。

awk -f translate.awk translate.txt input.txt

スクリプトには多数のエラーがあります。Effective AWK Programmingを読む必要があります。

于 2013-07-19T10:10:50.567 に答える
1

GNU のコード(Windows 引用):

sed -r "s#(\S+);(\S+)#/^\1,/s/.*,(\\S+)/\2,\\1/#" file1|sed -rf - file2

シェル セッション:

>タイプ file1 file2

ファイル1


e;エミル
f;フリードリヒ
g;グスタフ
h;ハインリッヒ
井田

ファイル2


e,111
f,222
g,333
h,444
i,555

>sed -r "s#(\S+);(\S+)#/^\1,/s/.*,(\\S+)/\2,\\1/#" ファイル1|sed -rf - ファイル2
エミール、111
フリードリヒ222
グスタフ、333
ハインリッヒ 444
井田 555
于 2013-07-19T10:57:41.740 に答える