Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash 带有comm命令的行号。可能吗?_Bash_Awk_Compare_Comm - Fatal编程技术网

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