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。注意顺序很重要!

  • 相关阅读:
    越长大越孤单
    关于ASP.NET 启动Process的讨论
    利用selenium开发一个功能测试的框架
    开博啦(上班时间)
    利用回发 实现一个简单的AutoComplete功能
    FIFO和双端口RAM
    8位定点数开方程序(贴下来以后研究)
    Eclipse下文件读取的问题:Failed to reading file xxxxx
    Error:NgdBuild:604解决方法(添加NGC文件方法)
    Mandelbrot:美丽的分形
  • 原文地址:https://www.cnblogs.com/DjangoBlog/p/4135431.html
Copyright © 2011-2022 走看看