【问题标题】:Appending using sed pattern after certain line number在某些行号之后使用 sed 模式附加
【发布时间】:2021-03-26 19:58:13
【问题描述】:

我正在使用以下命令在 AMP 之后附加字符串,但现在我想将 after 添加到 SET2 或第 9 行之后的 AMP,我们可以修改此命令以仅在 SET2 或第 9 行之后附加字符串吗?如果我只想添加到 SET1 AMP 或第 9 行之前,有人可以帮我执行命令吗,谢谢。

$ sed -i '/AMP/a Target4' test.txt
$ cat test.txt 
#SET1
AMP
Target 1
Target 2
AMP
Target 3
Target 4
Target 5
#Set2
AMP
Target 11
Target 12

注意上面的文字之间没有线。

【问题讨论】:

  • 新文本是否应该直接出现在下一行第三个“AMP”的下方?

标签: sed


【解决方案1】:

请您尝试以下方法:

sed -i '
/^#Set2/,${     ;# if the line starts with "#Set2", execute the {block} until the last line $
/AMP/a Target4  ;# append the string after "AMP"
}               ;# end of the block
' test.txt

如果您想在#Set2之前附加字符串,请尝试:

sed -i '
1,/^#Set2/ {    ;# excecute the {block} while the line number >= 1 until the line matches the pattern /^#Set2/
/AMP/a Target4
}
' test.txt

表达式address1,address2flip-flop 运算符。一旦 address1(行号、正则表达式或其他条件)满足, 操作员不断返回true,直到address2 相遇。
然后从address1 执行以下命令或块,直到 address2.

【讨论】:

  • 第一个工作但在 SET2 命令之前,它显示以下错误 sed -i '1,/^#Set2/ ${/AMP/a Target4}' test.txt sed: -e expression #1,字符 12:未知命令:`$'
  • 感谢您的反馈。请注意,{ 之前不是 $ 字符。在我的第二个答案中。使用剪切和粘贴来复制脚本可能会更好。
【解决方案2】:

如果您想添加到#Set2 或行号 9 之后的 AMP 之后, 我认为最好分别处理到第 8 行和第 9 行之后。

例如,命令如下:

sed '
1,8{
  /^#Set2/,${
    /AMP/a Target4
  }
}
9,${
  /AMP/a Target4
}' test.txt

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-28
    • 1970-01-01
    • 2020-05-11
    • 1970-01-01
    • 1970-01-01
    • 2016-08-27
    相关资源
    最近更新 更多