【问题标题】:Replace All Lines That Do Not Contain Matched String替换所有不包含匹配字符串的行
【发布时间】:2022-01-19 09:21:54
【问题描述】:

我正在处理这个看起来像这样的数据文件:

text in file
hello random text in file
example text in file
words in file hello
more words in file
hello text in file can be
more text in file

我正在尝试使用 sed 将所有 包含字符串 hello 的行替换为 match,因此输出将是:

match
hello random text in file
match
words in file hello
match
hello text in file can be
match

我尝试使用sed '/hello/!d',但这会删除该行。另外,我读到我可以在 sed 中使用 ! 进行匹配,但我不确定如何匹配每一行并正确替换。如果您能给我一些指导,我将不胜感激。

【问题讨论】:

    标签: linux bash awk sed


    【解决方案1】:

    你可以这样做:

    $ sed '/hello/!s/.*/match/' infile
    match
    hello random text in file
    match
    words in file hello
    match
    hello text in file can be
    match
    

    /hello/! 确保我们只替换不包含 hello 的行(你有这个权利),然后替换将完整的模式空间 (.*) 替换为 match

    【讨论】:

    • 肯定有路要走,出色的答案
    【解决方案2】:

    awk 来救援!

    $ awk '!/hello/{$0="match"}1' file
    

    将不匹配“hello”的行替换为“match”并打印所有行。

    【讨论】:

    • 嘿 Karakfa,这很好,但除了替换行之外,它还删除了其他行。
    • 不应该,1 可以打印所有行。
    • 啊,你说得对。谢谢你。我不太擅长 awk,但这很好用。
    【解决方案3】:

    使用c(更改)命令进行 Sed:

    $ sed '/hello/!c match' file
    match
    hello random text in file
    match
    words in file hello
    match
    hello text in file can be
    match
    

    【讨论】:

      【解决方案4】:

      为了清晰、简单等,只需使用 awk:

      awk '{print (/hello/ ? $0 : "match")}' file
      

      【讨论】:

        猜你喜欢
        • 2016-09-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-19
        • 2020-06-23
        • 1970-01-01
        • 2011-08-29
        • 1970-01-01
        相关资源
        最近更新 更多