AWK:比较两个文件中的两个不同的列 [英] AWK: Comparing two different columns in two files
本文介绍了AWK:比较两个文件中的两个不同的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这两个文件
文件1:
9 8 6 8 5 2
2 1 7 0 6 1
3 2 3 4 4 6
文件2 :(具有超过400万行)
File2: (which has over 4 million lines)
MN 1 0
JK 2 0
AL 3 90
CA 4 83
MK 5 54
HI 6 490
我想比较文件1的字段6和文件2的字段2.如果它们匹配,则将文件2的字段3放在文件1的末尾我已经查看了其他解决方案,但无法使其正常工作.
I want to compare field 6 of file1, and compare field 2 of file 2. If they match, then put field 3 of file2 at the end of file1 I've looked at other solutions but I can't get it to work correctly.
所需的输出:
9 8 6 8 5 2 0
2 1 7 0 6 1 0
3 2 3 4 4 6 490
我的尝试:
awk 'NR==FNR{a[$2]=$2;next}a[$6]{print $0,a[$6]}' file2 file1
程序随后挂起.
推荐答案
要在文件1中打印所有具有匹配项的行:
To print all lines in file1 with match if available:
$ awk 'FNR==NR{a[$2]=$3;next;} {print $0,a[$6];}' file2 file1
9 8 6 8 5 2 0
2 1 7 0 6 1 0
3 2 3 4 4 6 490
仅打印具有匹配项的行:
To print only the lines that have a match:
$ awk 'NR==FNR{a[$2]=$3;next} $6 in a {print $0,a[$6]}' file2 file1
9 8 6 8 5 2 0
2 1 7 0 6 1 0
3 2 3 4 4 6 490
请注意,我将 a [$ 2] = $ 2
替换为 a [$ 2] = $ 3
,并更改了测试 a [$ 6]
(如果值为零,则为false)到 $ 6 in
.
Note that I replaced a[$2]=$2
with a[$2]=$3
and changed the test a[$6]
(which is false if the value is zero) to $6 in a
.
这篇关于AWK:比较两个文件中的两个不同的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文