【问题标题】:How to use sed to exclude a word [duplicate]如何使用sed排除一个词[重复]
【发布时间】:2020-04-18 16:31:30
【问题描述】:

我正在尝试运行 sed 命令,通过排除以“This”开头的行来显示文件中的文本。我可以使用 grep 执行相同的操作,但使用 sed 时遇到问题。我尝试了以下命令:

sed -n '/[^This]/p' example

它正在打印整个文件。

This is first line of example text
It is a text with erors.
Lots of erors.
So much erors, all these erors are making me sick.
This is a line not containing any erorrs.
This is the last line.

提前感谢您的帮助!

【问题讨论】:

    标签: regex sed grep


    【解决方案1】:

    像这样:

    sed '/^This.*$/d' example 
    

    【讨论】:

    • 甚至,sed '/^This/d'
    • 这应该是答案:-)
    【解决方案2】:

    一种选择是跳过打印以This 开头的行。

    sed -n 's/^This// ; t end; p; :end'
    

    它的作用如下:

    1. 与您的尝试类似,它使用-n 选项来避免自动打印。
    2. 接下来,它会尝试用空字符串替换行首的This
    3. 我们只需要执行替换来激活以下t 命令,该命令直接分支到以下:end 标签。无论如何,该行都会被丢弃。
    4. 如果没有发生替换,因此 t 命令未激活,p 命令将打印出该行。

    结果是:

    It is a text with erors.
    Lots of erors.
    So much erors, all these erors are making me sick.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-02
      • 2019-03-07
      • 2011-05-31
      • 2020-11-08
      • 1970-01-01
      • 1970-01-01
      • 2018-11-06
      • 2016-04-28
      相关资源
      最近更新 更多