AWK、2つのファイルのフィールドを一致させてフィールド値を変更する

AWK、2つのファイルのフィールドを一致させてフィールド値を変更する

Address.csvとZipCode.txtという2つのファイルがあります。 Address.csvに似たファイルを作成し、郵便番号が郵便番号の最初の5文字と一致する場合は、都市フィールドを「city」から「found」に更新したいと思います。」 Address.csv ファイルにあります。

私が持っているもの:

  Address.csv
  Zip,Address1,Address2,conty,city,state
  65432-3421,115 main st,atlantic,city,new jersey
  45678-4098,654 2nd st n.,bergin,city,new jersey
  23456-3425,4215 1st st. s.,suite a2,camden,city,new jersey
  12345-6278,3587 main st,apt j1,essex,city,new jersey

  ZipCode.txt
  23456
  12345
  34567
  45678

私が望むもの:

  NewAddress.csv
  Zip,Address1,Address2,conty,city,state
  65432-3421,115 main st,atlantic,city,new jersey
  45678-4098,654 2nd st n.,bergin,found,new jersey
  23456-3425,4215 1st st. s.,suite a2,camden,found,new jersey
  12345-6278,3587 main st,apt j1,essex,found,new jersey

Simlevの助けを借りて試したことawk は、他のファイルの一致する値に基づいてフィールド値を置き換えます。:

  awk -F, -v OFS="," 'NR==FNR {a[$1]++;next} $1 in a {$4="found"} 1' ZipCode.txt Address.csv     

ベストアンサー1

スクリプトで変更する主な点は、最初のフィールドの最初の5文字を​​取得する関数を使用することですsubstr

内部データAddress.csvが一致しません。最初の2つのデータラインには5つのフィールドがあり、他のデータラインには6つのフィールドがあります。これが(4番目のフィールド)の$(NF-1)代わりに(最後の2番目のフィールド)を使用する理由です$4。それ以外の場合、サンプルデータは無効なフィールドを変更します。

awk -F, -v OFS="," 'NR==FNR {a[$1]++;next} substr($1,1,5) in a {$(NF-1)="found"} 1' ZipCode.txt Address.csv

この印刷

Zip,Address1,Address2,conty,city,state
65432-3421,115 main st,atlantic,city,new jersey
45678-4098,654 2nd st n.,bergin,found,new jersey
23456-3425,4215 1st st. s.,suite a2,camden,found,new jersey
12345-6278,3587 main st,apt j1,essex,found,new jersey

おすすめ記事