zoukankan      html  css  js  c++  java
  • LINUX Shell 下求两个文件交集和差集的办法

    http://blog.csdn.net/autofei/article/details/6579320

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

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

    FILE2内容如下:

    [xhtml] view plaincopy
     
    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 plaincopy
     
    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 plaincopy
     
    1. $ comm <(sort a.txt ) <(sort b.txt )  
    2.                 a  
    3. a  
    4. b  
    5.                 c  
    6.         c  
    7.                 d  
    8. e  

    排序并且唯一:

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

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

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

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

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

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

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

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

    差集呢?

    [xhtml] view plaincopy
     
    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。注意顺序很重要!

  • 相关阅读:
    附近有什么?8款可以查周边的App
    实体店里充话费要怎么弄
    怎样买手机号?
    手机号是SIM卡的号呢,还是买手机时就带的
    网站SSL证书在线检测
    未来什么行业最赚钱
    陈安之-如何选择最赚钱的行业
    斗鱼宣布获C轮15亿融资 直播行业进入资本时代
    2016年Godaddy最新域名转出教程
    GoDaddy账户间域名转移PUSH以及ACCEPT接受域名过户方法
  • 原文地址:https://www.cnblogs.com/DjangoBlog/p/4135431.html
Copyright © 2011-2022 走看看