【问题标题】:Insert text in the middle of a text file after the first occurence of a search string using sed使用 sed 在第一次出现搜索字符串后在文本文件中间插入文本
【发布时间】:2014-02-03 17:07:40
【问题描述】:

我想知道是否可以在使用 GNU sed 首次出现搜索字符串之后在文本文件的中间插入一些文本。

例如,如果搜索字符串是“Hello”,我想在新行第一次出现“Hello”之后插入一个字符串

Hello John, How are you?
....
....
....
Hello Mary, How are you doing? 

字符串将在“Hello John, How are you?”之后输入。换行

谢谢,

【问题讨论】:

标签: bash sed


【解决方案1】:

你可以说:

sed '/Hello/{s/.*/&\nSomething on the next line/;:a;n;ba}' filename

为了在所需字符串的第一次出现之后插入一行,例如Hello 就像你的问题一样。

对于您的示例数据,它会产生:

Hello John, How are you?
Something on the next line
....
....
....
Hello Mary, How are you doing? 

【讨论】:

    【解决方案2】:

    使用 sed:

    sed '/Hello John, How are you?/s/$/\nsome string\n/' file
    Hello John, How are you?
    some string
    
    ....
    ....
    ....
    Hello Mary, How are you doing? 
    

    【讨论】:

    • 感谢您的回答,我选择了 devnull 的回答,因为它更笼统。
    • 不确定我的一般情况或他的回答,两者都产生相同的输出。但为了更好的便携解决方案,请始终考虑 awk 而不是 sed。
    【解决方案3】:

    使用awk

    awk '/Hello/ && !f {print $0 "\nNew line";f=1;next}1' file
    Hello John, How are you?
    New line
    ....
    ....
    ....
    Hello Mary, How are you doing?
    

    搜索 sting Hello 并且如果标志 f 不为真(开始时默认)
    如果为真,则打印该行,打印额外文本,将标志 f 设置为 true,跳到下一行。
    下次发现Hello 标志f 为真,不会做任何额外的事情。

    【讨论】:

      【解决方案4】:
      sed '/Hello/ a/
      Your message with /
      New line' YourFile
      

      a/ 用于追加(之后)您要查找的模式,i/ 用于插入(之前)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-10-15
        • 1970-01-01
        • 2019-08-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多