Linux 對比兩個文字的交集和差集(comm)

pursuer.chen發表於2016-06-02

介紹

comm命令可以對兩個已排序好的文字的內容進行交集和差集的對比,記住必須是已排序過的檔案;可以使用sort命令對沒有排序的檔案進行排序,comm命令在對比結果中會產生三列分別是:在A中不在B中的內容,在B中不在A中的內容,AB的交集的內容。

 

 

事例

[root@localhost test]# cat a
3 c
2 b
1 a

[root@localhost test]# cat b
2 b
3 c
4 d

其中檔案a不是倒序的檔案,看看直接拿來對比會出現什麼問題。

[root@localhost test]# comm a b
    2 b
        3 c
comm: file 1 is not in sorted order
2 b
1 a

    4 d

對比結果出現了問題提示檔案1不是已排序的檔案。

1.對檔案進行排序

[root@localhost test]# sort a -o a
[root@localhost test]# cat a
1 a
2 b
3 c

2.對比檔案

[root@localhost test]# comm a b
1 a
        2 b
        3 c
    4 d

第一列:在a檔案中不在b檔案中的內容

第二列:在b檔案中不在a檔案中的內容

第三列:a檔案和b檔案的交集

comm命令引數

-1:不顯示第一列

-2:不顯示第二列

-3:不顯示第三列

[root@localhost test]# comm a b -1
    2 b
    3 c
4 d
[root@localhost test]# comm a b -2
1 a
    2 b
    3 c
[root@localhost test]# comm a b -3
1 a
    4 d
[root@localhost test]# comm a b -12
2 b
3 c

其它的一些特殊處理方法

[root@localhost test]# comm a b -3
1 a
    4 d
[root@localhost test]# comm a b -3 | sed 's/^\t//'
1 a
4 d

可以使用sed命令將開頭的製表符(tab)替換掉,s:替換的意思,^:以什麼開頭,\t:製表符,//:空

總結

 

 

 

 

備註:

    作者:pursuer.chen

    部落格:http://www.cnblogs.com/chenmh

本站點所有隨筆都是原創,歡迎大家轉載;但轉載時必須註明文章來源,且在文章開頭明顯處給明連結。

《歡迎交流討論》

相關文章