【问题标题】:Using sed to remove lines from a txt file使用 sed 从 txt 文件中删除行
【发布时间】:2013-02-27 20:26:01
【问题描述】:

我有一个大文本文件,我想从中删除另一个文本文件中的一些行。似乎 Unix shell 中的 sed 命令是一个很好的方法。但是,我无法弄清楚为此使用哪些标志。 .

数据库.txt:

this is line 1
this is line 2
this is line 3
this is line 4
this is line 5

lines_to_remove.txt

this is line 1
this is line 3

what_i_want.txt

this is line 2
this is line 4
this is line 5

【问题讨论】:

    标签: shell unix sed awk grep


    【解决方案1】:

    grepsed 更适合这个:

    grep -Fxv -f lines_to_remove.txt database.txt > what_i_really_really_want.txt
    

    【讨论】:

    • 您确定该命令有效还是在我这边?我收到了grep: Invalid back reference
    • 您的lines_to_remove.txt 文件必须包含一些特殊字符。尝试添加-F。正在编辑...
    • 如果 database.txt 有 this is line 10 之类的内容,将无法正常工作。您应该添加 -x 以匹配整行。
    【解决方案2】:

    我会为此使用comm

    comm -1 <(sort database.txt) <(sort lines_to_remove.txt) > what_i_want.txt
    

    该命令更适合您的需求。

    注意&lt;(commmand) 语法是一种 bashism,因此在 SO 上受到很多诽谤。它是以下内容的简写:

    sort database.txt > sorted_database.txt
    sort lines_to_remove.txt > sorted_lines_to_remove.txt
    comm -1 sorted_database.txt sorted_lines_to_remove.txt > what_i_want.txt
    

    【讨论】:

      【解决方案3】:

      awk:

      $ awk 'NR==FNR{a[$0];next}!($0 in a)' remove.txt database.txt
      this is line 2
      this is line 4
      this is line 5
      
      $ awk 'NR==FNR{a[$0];next}!($0 in a)' remove.txt database.txt > output.txt
      

      【讨论】:

      • +1 用于解决方案,但我建议您不要使用字母 l (el) 作为变量名,因为它看起来太像数字 1 (one) 并且是偶数在某些字体中无法区分,因此会混淆您的代码。字母O(哦)与数字0(零)同上。
      猜你喜欢
      • 1970-01-01
      • 2011-12-15
      • 2023-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      • 2012-04-13
      相关资源
      最近更新 更多