簡體   English   中英

帶有 comm 命令的行號。 是否可以?

[英]Line number with comm command. Is it possible?

我用這個命令比較兩個文件

comm -13 file1 file2

它工作得很好,並告訴我差異。 但我還想向我展示行號(在第二個文件中唯一的行)。

文件 1:

a
d
e
f
g

文件2:

a
b
c
d
e

我願意:

 comm -13 file1 file2

輸出

b
c

但我需要 b 和 c 在 file2 中的行號,所需的輸出:

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
}
{
    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

例如,使用包含額外d行的修改后的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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM