我有 2 个文件 Address.csv 和 ZipCode.txt,我想生成一个与 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
脚本中需要更改的主要内容是使用 function 获取第一个字段的前 5 个字符substr
。
里面的数据Address.csv
不一致。前两条数据线有 5 个字段,其他数据线有 6 个字段。这就是为什么我使用$(NF-1)
(倒数第二个字段)而不是$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