Bash 带有comm命令的行号。可能吗?
我用这个命令比较两个文件Bash 带有comm命令的行号。可能吗?,bash,awk,compare,comm,Bash,Awk,Compare,Comm,我用这个命令比较两个文件 comm -13 file1 file2 它完美地工作,告诉我不同之处。但我想给我看一下行号(第二个文件中唯一的行) 文件1: a d e f g 文件2: a b c d e 我有: 输出 b c 但我需要文件2中b和c所在的行号,所需输出: 2 3 使用awk: $ awk 'NR==FNR{a[$0];next}!($0 in a){print FNR}' file1 file2 输出: 2 3 编辑:如OP中所示,当文件file2有重复项时,co
comm -13 file1 file2
它完美地工作,告诉我不同之处。但我想给我看一下行号(第二个文件中唯一的行)
文件1:
a
d
e
f
g
文件2:
a
b
c
d
e
我有:
输出
b
c
但我需要文件2中b和c所在的行号,所需输出:
2
3
使用awk:
$ awk 'NR==FNR{a[$0];next}!($0 in a){print FNR}' file1 file2
输出:
2
3
编辑:如OP中所示,当文件file2
有重复项时,comm
的行为不同。下面的解决方案应该可以解决这个问题(请参阅评论并感谢@EdMorton):
希望没有那么多的陷阱等待着你
awk 'NR==FNR{a[$0]++; next} (--a[$0]) < 0{print FNR}' file1 file2
$awk'NR==FNR{a[$0]++;next}(-a[$0])<0'文件1文件2
B
C
D
$awk'NR==FNR{a[$0]+;next}(-a[$0])<0{print FNR}文件1文件2
2.
3.
5.
这不太一样。将第二行d
添加到文件a
中,然后尝试comm-13 b a
和您的awk命令,您会发现前者正确输出d
,而后者不会输出与d
关联的行号,因为它不考虑重复项。
$ awk '
NR==FNR {
a[$0]++
next
}
{
if(!($0 in a)||a[$0]<=0)
print FNR
else a[$0]--
}' file1 file2
2
3
5
awk 'NR==FNR{a[$0]++; next} (--a[$0]) < 0{print FNR}' file1 file2
$ 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