【问题标题】:Remove line from file that contains string more than once从包含多次字符串的文件中删除行
【发布时间】:2021-08-09 16:37:56
【问题描述】:

我需要删除文件中多次包含某个字符串的所有行,例如,如果我的文件是这样的:

This is a test toRemove first line

This is a test toRemove second line toRemove

应该生成一个只有第一行的文件

This is a test toRemove first line

我正在尝试从命令行在 linux 上执行此操作,我尝试像这样使用 grep 或 sed

grep -d "toRemove.*toRemove" myFile > myOtherFile

sed '/\toRemove.*toRemove/!d' myFile > myOtherFile

但似乎没有任何效果。有谁知道如何获得这个?

【问题讨论】:

  • 应该是sed '/toRemove.*toRemove/d' myFile > myOtherFile\t 匹配 TAB 字符,!d 删除不匹配模式的行
  • grep -v "toRemove.*toRemove" myFile > myOtherFile 应该可以工作。

标签: regex sed command-line grep


【解决方案1】:

你可以使用

sed '/toRemove.*toRemove/d' myFile > myOtherFile
grep -v "toRemove.*toRemove" myFile > myOtherFile

sed:请注意,\t 匹配 TAB 字符,!d 删除与模式不匹配的行。因此,您需要在t 之前删除\,并在d 之前删除!

grep:您应该使用-v 选项来反转正则表达式检查的结果(它将输出所有与模式不匹配的行)。

online demo

s='This is a test toRemove first line
This is a test toRemove second line toRemove'
sed '/toRemove.*toRemove/d' <<< "$s"
# => This is a test toRemove first line
grep -v 'toRemove.*toRemove' <<< "$s"
# => This is a test toRemove first line

【讨论】:

    【解决方案2】:

    这可能对你有用(GNU sed):

    sed '/\<\(toRemove\)\>.*\<\1\>/d' file
    

    这将删除出现 2 次或更多单词 toRemove 的行。

    要删除包含单词toRemove 的任何行,超出第一行:

    sed '/\<toRemove\>/{x;/./{x;d};x;h}' file
    

    【讨论】:

      猜你喜欢
      • 2014-04-24
      • 2013-10-27
      • 2014-04-16
      • 2021-03-17
      • 2018-07-06
      • 1970-01-01
      • 2011-05-30
      • 1970-01-01
      相关资源
      最近更新 更多