![awk 根据另一个文件中的匹配值替换字段值](https://linux22.com/image/154733/awk%20%E6%A0%B9%E6%8D%AE%E5%8F%A6%E4%B8%80%E4%B8%AA%E6%96%87%E4%BB%B6%E4%B8%AD%E7%9A%84%E5%8C%B9%E9%85%8D%E5%80%BC%E6%9B%BF%E6%8D%A2%E5%AD%97%E6%AE%B5%E5%80%BC.png)
我有 2 个文件,Zipcode.txt
并且Address.csv
:
ZipCode.txt
12345
23456
34567
45678
Address.csv
12345,3587 main st,apt j1,city,new jersey
23456,4215 1st st. s.,suite a2,city,new jersey
65432,115 main st,,city,new jersey
45678,654 2nd st n.,city,new jersey
如果 中的邮政编码字段Zipcode.txt
与 中的邮政编码字段匹配Address.csv
,我想将第四个字段从 更改city
为found
。这就是我想要的:
12345,3587 main st,apt j1,found,new jersey
23456,4215 1st st. s.,suite a2,found,new jersey
65432,115 main st,,city,new jersey
45678,654 2nd st n.,found,new jersey
这是我尝试过的:
awk -F',' 'BEGIN{OFS=FS}NR==FNR{a[$1]=1;next}a[$1]{$4="found"}1' Address.csv ZipCode.txt
答案1
这将搜索 的第一个字段中的邮政编码是否Address.csv
在 中的任何位置找到Zipcode.txt
:
awk -F, -v OFS="," 'NR==FNR {a[$1]++;next} $1 in a {$4="found"} 1' Zipcode.txt Address.csv
输出:
12345,3587 main st,apt j1,found,new jersey
23456,4215 1st st. s.,suite a2,found,new jersey
65432,115 main st,,city,new jersey
45678,654 2nd st n.,city,found
请注意,最后一行与预期不符,因为city
不是输入中的第四个字段:最后一行中可能缺少逗号Address.csv
。