问题描述
我用这个命令比较两个文件
comm -13 file1 file2
它运作完美,并告诉我与众不同。但我也想告诉我行号(第二个文件中唯一的行)。
文件1:
a
d
e
f
g
文件2:
a
b
c
d
e
我愿意:
comm -13 file1 file2
b
c
但是我需要file2中b和c所在的行号,期望的输出:
2
3
解决方法
使用awk:
$ awk 'NR==FNR{a[$0];next}!($0 in a){print FNR}' file1 file2
输出:
2
3
编辑:如OP中所述,当文件comm
具有重复项时,file2
的行为有所不同。下面的解决方案应解决此问题(请参阅评论并感谢@EdMorton):
$ awk '
NR==FNR {
a[$0]++
next
}
{
if(!($0 in a)||a[$0]<=0)
print FNR
else a[$0]--
}' file1 file2
现在输出(file2
具有重复的条目d
,其中FNR==5
):
2
3
5
希望没有更多的陷阱等待着……
,awk 'NR==FNR{a[$0]++; next} (--a[$0]) < 0{print FNR}' file1 file2
例如使用经过修改的file2
(其中包括额外的d
行)来证明正确处理了重复值:
$ cat file2
a
b
c
d
d
e
$ comm -13 file1 file2
b
c
d
$ awk 'NR==FNR{a[$0]++; next} (--a[$0]) < 0' file1 file2
b
c
d
$ awk 'NR==FNR{a[$0]++; next} (--a[$0]) < 0{print FNR}' file1 file2
2
3
5