比较两个文件并输出同一行的程序



我有一个问题。我想创建一个程序,它打印第一个文件和第二个文件中的所有行。

awk 'NR==FNR {include[$0];next} $0 in include' eq3_dgdg_1.ndx eq3_dgdg_2.ndx | tee eq4_dgdg_2.ndx

eq3_dgdg_1。ndx输入

DGD1 SOL3605
DGD2 SOL1176
DGD2 SOL1598
DGD2 SOL63

eq3_dgdg_2.ndx

DGD1 SOL3605
DGD1 SOL3605
DGD2 SOL1176
DGD2 SOL1176
DGD2 SOL1945
DGD2 SOL63

输出-这里有一个错误DGD1 SOL3605 -应该只有一次!因为我在第一个文件中只有一行DGD1 SOL3605,而不是两行,你能帮我解决这个错误吗?

DGD1 SOL3605
DGD1 SOL3605
DGD2 SOL1176
DGD2 SOL63

预期输出

DGD1 SOL3605
DGD2 SOL1176
DGD2 SOL63

如果文件中允许重复行,则需要计数器。试试吧:

awk 'NR==FNR{a[$0]++;next}a[$0]-->0' f1 f2

让我们用你的数据做一个测试:

kent$  head f*
==> f1 <==
DGD1 SOL3605
DGD2 SOL1176
DGD2 SOL1598
DGD2 SOL63
==> f2 <==
DGD1 SOL3605
DGD1 SOL3605
DGD2 SOL1176
DGD2 SOL1945
DGD2 SOL63
kent$  awk 'NR==FNR{a[$0]++;next}a[$0]-->0' f1 f2
DGD1 SOL3605
DGD2 SOL1176
DGD2 SOL63

基于对你问题的一种可能的解释:

$ sort -u file2 | awk 'NR==FNR{a[$0];next} $0 in a' file1 -
DGD1 SOL3605
DGD2 SOL1176
DGD2 SOL63

或awk:

$ awk 'NR==FNR{a[$0];next} $0 in a{print; delete a[$0]}' file1 file2
DGD1 SOL3605
DGD2 SOL1176
DGD2 SOL63

请尝试以下操作。在GNUawk中编写并使用所示示例进行了测试。

awk 'FNR==NR{arr[$0];next} ($0 in arr) && !arr2[$0]++' eq3_dgdg_1.ndx eq3_dgdg_2.ndx

解释:为以上内容添加详细说明。

awk '                             ##Starting awk program from here.
FNR==NR{                          ##Checking condition FNR==NR for first file processing.
arr[$0]                         ##Creating arr with index of current line.
next                            ##next will skip all further statements from here.
}
($0 in arr) && !arr2[$0]++        ##Checking if current line present in arr AND current line coming first time in arr2 then print it.
' eq3_dgdg_1.ndx eq3_dgdg_2.ndx   ##Mentioning Input_file name here.

最新更新