[Shell]比較兩個文件內容

comm -3 file1 file2

功能:逐行比较两个排好序的文件,默认输出有三列:只在file1中有的行、只在file2中有的行、在file1和file2中共有的行。有参数-1, -2, -3,分别来抑制输出对应的列。例如,实用-3参数,不输出file1和file2中共有的部分。即能达到我们本文的目的。
但是注意到,comm比较排好序的两个文件,comm在处理文件的时候,首先要查看文件是否有序,例如file1和file2的内容如下:

  1. $cat file1  
  2. line1  
  3. line2  
  4. line3   

  1. $cat file2  
  2. line0  
  3. line1  
  4. line3  
  5. line2  

调用comm命令时,会提示file2文件时无序的,输出的结果如下:

$ comm -3 file1 file2
        line0
line2
comm: file 2 is not in sorted order
        line2

如果使用--nocheck-order参数,不进行有序性检测,结果如下:

$ comm -3 --nocheck -order file1 file2

        line0
        line2

        line2


统计两个文本文件的相同行

          grep -Ff file1 file2

统计file2中有,file1中没有的行

         grep -vFf file2 file1

如何比较两个文件并删除相同的内容

        for i in $(<file1); do grep $i file2 || echo $i >>tmp1 ; done

输出相同行:

        grep -wf file1 file2

输出不同行:

        grep -wvf file1 file2

ref : link1

发布了89 篇原创文章 · 获赞 17 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/lbt_dvshare/article/details/89632392