【转】LINUX Shell 下求两个文件交集和差集的办法

假设两个文件FILE1和FILE2用集合A和B表示,FILE1内容如下:

 

[xhtml] view plain copy
 
  1. a  
  2. b  
  3. c  
  4. e  
  5. d  
  6. a  

 

FILE2内容如下:

 

[xhtml] view plain copy
 
  1. c  
  2. d  
  3. a  
  4. 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。

直接运行结果如下:

 

[xhtml] view plain copy
 
  1. $ comm a.txt b.txt  
  2. a  
  3. b  
  4.                 c  
  5.         d  
  6.         a  
  7.         c  
  8. e  
  9. d  
  10. a  

 

仅仅排序:

 

[xhtml] view plain copy
 
  1. $ comm <(sort a.txt ) <(sort b.txt )  
  2.                 a  
  3. a  
  4. b  
  5.                 c  
  6.         c  
  7.                 d  
  8. e  

 

排序并且唯一:

 

[xhtml] view plain copy
 
  1. $ comm <(sort a.txt|uniq ) <(sort b.txt|uniq )  
  2.                 a  
  3. b  
  4.                 c  
  5.                 d  
  6. e  

 

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

 

[xhtml] view plain copy
 
  1. $ comm -12 <(sort a.txt|uniq ) <(sort b.txt|uniq )  
  2. a  
  3. c  
  4. d  

 

至于差集,读者自己思考了。

 

grep 命令是常用的搜索文本内容的,要找交集,如下即可:

 

[xhtml] view plain copy
 
  1. p$ grep -F -f a.txt b.txt  
  2. c  
  3. d  
  4. a  
  5. c  

 

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

 

[c-sharp] view plain copy
 
  1. $ grep -F -f a.txt b.txt | sort | uniq  
  2. a  
  3. c  
  4. d  

 

差集呢?

 

[xhtml] view plain copy
 
  1. $ grep -F -v -f a.txt b.txt | sort | uniq  
  2. $ grep -F -v -f b.txt a.txt | sort | uniq  
  3. b  
  4. e  

 

第一行结果为B-A,所以为空;第二行为A-B。注意顺序很重要!

posted on 2016-03-31 17:04  月未央  阅读(676)  评论(0编辑  收藏  举报

导航