1. 程式人生 > >LINUX Shell 下求兩個檔案交集和差集的辦法

LINUX Shell 下求兩個檔案交集和差集的辦法

轉載自https://blog.csdn.net/autofei/article/details/6579320

假設兩個檔案FILE1和FILE2用集合A和B表示,FILE1內容如下:

a  
b  
c  
e  
d  
a  

FILE2內容如下: 

c  
d  
a  
c

基本上有兩個方法,一個是comm命令,一個是grep命令。分別介紹如下:

 

comm命令 , Compare sorted files FILE1 and FILE2 line by line. With  no options, produce three-column output.  Column one contains lines unique to FILE1, column two contains lines unique to FILE2, and column three contains lines common to both files. 要注意兩個檔案必須是排序和唯一(sorted and unique)的,預設輸出為三列,第一列為是A-B,第二列B-A,第三列為A交B。

直接執行結果如下:
 

$ comm a.txt b.txt  
a  
b  
                c  
        d  
        a  
        c  
e  
d  
a  

僅僅排序

$ comm <(sort a.txt ) <(sort b.txt )  
                a  
a  
b  
                c  
        c  
                d  
e  

排序並且唯一:

$ comm <(sort a.txt|uniq ) <(sort b.txt|uniq )  
                a  
b  
                c  
                d  
e  

如果只想要交集,如下即可:

$ comm -12 <(sort a.txt|uniq ) <(sort b.txt|uniq )  
a  
c  
d  

grep 命令是常用的搜尋文字內容的,要找交集,如下即可:

p$ grep -F -f a.txt b.txt  
c  
d  
a  
c 

 grep不要求排序,但是因為是集合操作,唯一是必須的(不然怎麼是集合呢?)。所以:

$ grep -F -f a.txt b.txt | sort | uniq  
a  
c  
d 

 差集呢?

$ grep -F -v -f a.txt b.txt | sort | uniq  
$ grep -F -v -f b.txt a.txt | sort | uniq  
b  
e  

第一行結果為B-A,所以為空;第二行為A-B。注意順序很重要!