【问题标题】:sed insert newline after matchsed 在匹配后插入换行符
【发布时间】:2021-04-11 21:20:07
【问题描述】:

我有一个包含以下内容的变量:

k1065-betfirst-4ccc6a2cf196 (192.168.255.46) is off-line k1164-betfirst-4ccc6a8ff0be (192.168.255.54) is off-line K1165-BetFirst-4ccc6a2cf343 (192.168.255.26) is off-line K1185-BetFirst-4ccc6aba7af7 (192.168.255.18) is off-line k1331-betfirst-448a5bb71eb8 (192.168.255.38) is off-line

我需要在“line”换行符之后插入。为此,我使用 sed:

echo -e $mailbody | sed 's/line/\n&/g' | tee -a hosts2.txt

但它在“行”之前插入换行符:

 k1065-betfirst-4ccc6a2cf196 (192.168.255.46) is off-
line k1164-betfirst-4ccc6a8ff0be (192.168.255.54) is off-
line K1165-BetFirst-4ccc6a2cf343 (192.168.255.26) is off-
line K1185-BetFirst-4ccc6aba7af7 (192.168.255.18) is off-
line k1331-betfirst-448a5bb71eb8 (192.168.255.38) is off-
line

谁能给我一个提示,如何重写sed,在“line”之后写换行符?

【问题讨论】:

  • 那么,交换\n&sed 's/line/&\n/g'?

标签: bash sed


【解决方案1】:

尝试交换&\n。另外,您可能需要删除line 后面的空格:

's/line */&\n/g'

【讨论】:

    【解决方案2】:

    参考this resource 有很多很好的例子。例如:

    # insert a blank line below every line which matches "regex"
    sed '/regex/G'
    

    【讨论】:

    • 注意 - 这可能不是我们想要的……但资源仍然很好,this one
    【解决方案3】:

    在 BSD/macOS sed 中,必须使用带有 \-escape 的文字换行符:

    's/line */\
    /g'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-11
      • 1970-01-01
      • 1970-01-01
      • 2020-01-14
      • 1970-01-01
      • 2014-03-18
      相关资源
      最近更新 更多