Linux comm命令求出文件的交集、差集

A(1,2,3)和B(3,4,5),A和B的交集是3,A對B的差集是1和2,B對A的差集是4和5,A和B求差的結果是一、二、四、5。cookie

在Linux中可使用comm命令求出這些集。app

[root@xuexi tmp]# cat <<eof>set1.txt
> orange
> gold
> apple
> sliver
> steel
> iron
> eof
[root@xuexi tmp]# cat <<eof>set2.txt
> orange
> gold
> cookiee
> carrot
> eof

使用comm命令。spa

[root@xuexi tmp]# comm set1.txt set2.txt
apple
                orange
comm: file 1 is not in sorted order
comm: file 2 is not in sorted order
                gold
        cookiee
        carrot
silver
steel
iron

提示沒有排序,因此comm必需要保證比較的文件是有序的。code

[root@xuexi tmp]# sort set1.txt -o set1.txt;sort set2.txt -o set2.txt
[root@xuexi tmp]# comm set1.txt set2.txt                             
apple
        carrot
        cookiee
                gold
iron
                orange
silver
steel

結果中輸出了3列,每一列使用製表符\t隔開。第一列是set1.txt中有而set2.txt中沒有的,第二列則是set2.txt中有而set1.txt中沒有的,第三列是set1.txt和set2.txt中都有的。blog

根據這三列就能夠求出交集、差集和求差。排序

交集就是第三列。使用-1和-2分別刪除第一第二列就是第三列的結果。class

[root@xuexi tmp]# comm set1.txt set2.txt -1 -2
gold
orange

A對B的差集就是第一列,B對A的差集就是第二列。file

[root@xuexi tmp]# comm set1.txt set2.txt  -2 -3  # A對B的差集
apple
iron
silver
steel
[root@xuexi tmp]# comm set1.txt set2.txt  -1 -3   # B對A的差集
carrot
cookiee

A和B的求差就是第一列和第二列的組合。sort

[root@xuexi tmp]# comm set1.txt set2.txt  -3  
apple
        carrot
        cookiee
iron
silver
steel

可是這樣分兩列的結果不方便查看,應該進行處理使它們顯示在同一列上。di

[root@xuexi tmp]# comm set1.txt set2.txt  -3 | tr "\t" "\0"
apple
carrot
cookiee
iron
silver
steel
相關文章
相關標籤/搜索