【问题标题】:Compare 2 files and extract lines that are different比较 2 个文件并提取不同的行
【发布时间】:2017-07-19 05:35:34
【问题描述】:

例如,我有 2 个文件:

文件 1:

1 azer 4
2 toto 0
3 blabla 8
4 riri 9
5 coco 2

文件 2:

1 azer 4
2 toto 0
3 blabla 8

我想比较两个文件,如果文件2中的行在文件1中,我想从文件1中删除那些行。例如:

输出:

4 riri 9
5 coco 2

我试过这个命令,但它只显示了相似之处:

awk 'NR==FNR{a[$2];next} $1 in a {print $0}' merge genotype.txt

有人知道怎么做吗?我在 awk 中尝试过,但如果可以在 R 或 python 中做到这一点,那也很好。

【问题讨论】:

标签: python r awk comparison


【解决方案1】:

首先,将文件 2 行读取为 set,以便测试更快。然后遍历文件 1 的行并使用生成器理解写入输出文件行。

with open("file2.txt") as f: file2 = set(f)

with open("file1.txt") as fr, open("file3.txt","w") as fw:
    fw.writelines(l for l in fr if l not in file2)
  • 订单保留
  • 快速测试
  • 文件 1 永远不会在内存中完全读取,但迭代器链会逐行读取/写入文件

【讨论】:

    【解决方案2】:
    # awk
    awk 'FNR==NR{a[$0];next}!($0 in a)' file2 file1
    
    # comm
    comm -23 file1 file2
    
    # grep 
    grep -Fvxf file2 file1
    

    输入

    $ cat file1
    1 azer 4
    2 toto 0
    3 blabla 8
    4 riri 9
    5 coco 2
    
    $ cat file2
    1 azer 4
    2 toto 0
    3 blabla 8
    

    输出

    $ awk 'FNR==NR{a[$0];next}!($0 in a)' file2 file1
    4 riri 9
    5 coco 2
    
    $ comm -23 file1 file2
    4 riri 9
    5 coco 2
    
    $ grep -Fvxf file2 file1
    4 riri 9
    5 coco 2
    

    【讨论】:

      【解决方案3】:

      grep中的一个更简单的解决方案-

      $cat file1
      1 azer 4
      2 toto 0
      3 blabla 8
      4 riri 9
      5 coco 2
      
      $cat file2
      1 azer 4
      2 toto 0
      3 blabla 8
      

      试试-

      grep -vf file2 file1
      

      输出-

      4 riri 9
      5 coco 2
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-05-25
        • 1970-01-01
        • 1970-01-01
        • 2018-02-27
        • 2018-09-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多