我有awk命令输出匹配的行数据比较2列,虽然我想输出相反的、不匹配的数据。
#file1.csv
box1,apple
box2,banana
#file2.csv
data24,box1,apple,text
date25,box1,banana,text
通过AWK,我有
awk -F',' 'NR==FNR{a[$1,$2]; next} ($2,$3) in a' file1.csv file2.csv
输出如下:
data24,box1,apple,text
和希望有:
banana,box2
在这种情况下,简单的否定似乎不起作用,请问您有什么建议吗?Have try:
awk -F',' 'NR==FNR{a[$1,$2]=1; next} !($2,$1) in a' file1.csv file2.csv
将输出:
data24,box1,apple,text
date25,box1,banana,text
$ awk 'BEGIN{FS=OFS=","} NR==FNR{a[$2,$3]; next} !(($1,$2) in a){print $2, $1}' file2.csv file1.csv
banana,box2
您可以反转操作,而不是反转逻辑:
awk -F',' 'NR==FNR{a[$1,$2]; next} ($2,$3) in a {next}1' file1.csv file2.csv
date25,box1,banana,text
或:
awk 'BEGIN{FS=OFS=","}
NR==FNR{a[$1,$2]; next} ($2,$3) in a {next} {print $2, $3}' file1.csv file2.csv
box1,banana
假设:
- 两个文件以逗号分隔
- 查找
file1.csv
中与file2.csv
中字段#2和#3不匹配的行 - 对于这些条目(来自
file1.csv
),按相反顺序打印字段(OP显示了banana,box2
的最终输出,这是file1.csv
中列出的box2,banana
的相反顺序)
对OP的awk
代码的一些修改:
awk '
BEGIN { FS=OFS="," }
NR==FNR { a[$1 FS $2] ; next } # add a delimiter to allow for splitting of index later
{ delete a[$2 FS $3] } # delete file #1 entries if found in file #2
END { for (i in a) { # anything left in array was not found in file #2
split(i,arr,FS) # split index on delimiter
print arr[2],arr[1] # print fields in reverse order
}
}
' file1.csv file2.csv
由此产生:
banana,box2