【问题标题】:sed: search for a pattern after a particular line containing a keywordsed:在包含关键字的特定行之后搜索模式
【发布时间】:2022-10-20 19:18:26
【问题描述】:

输入文件:

new file
myString
abc
myString
xyz
pattern
file txt
myString
almost the end of file
myString
end of file

输入文件在整个文件中包含多次出现的myString,但我只需要替换出现在另一个模式pattern 之后的myString 的第一次出现。

此外,pattern 和首次出现的myString 之间没有特定的行数。

所需的输出:

new file
myString
abc
myString
xyz
pattern
file txt
replacement_pattern
almost the end of file
myString
end of file

如果可能,我想使用sed 来完成这项任务

【问题讨论】:

  • 您是否尝试阅读sed 的介绍?
  • @tripleee 在问这里之前我已经对此做了很多研究......但对我来说没有任何效果
  • 请查看help center,尤其是How to ask,以及提供minimal reproducible example 的指南。
  • @tripleee 抱歉,我对这个平台比较陌生.. 仍然每天都在学习。如果您也可以帮助我解决我的问题,那就太好了。
  • 如果您在我的第一条评论中尝试了建议,那就太好了。一旦您学习了基础知识(尽管并非完全微不足道),您所问的问题就不难做到,当互联网上充斥着现有的介绍时,在答案中向您解释它们将是乏味的。

标签: parsing sed


【解决方案1】:

这可能对你有用(GNU sed):

sed '/pattern/{:a;N;s/myString/myReplacement/;Ta}' file

在找到包含pattern 的行后收集行并将第一个匹配项替换为替换字符串。

选择:

sed '/pattern/{:a;n;/myString/!ba;s//myReplacement/}' file

相同的想法,但使用传统的 sed 命令而不是特定于 GNU 的命令。

注:此解决方案使用n 而不是N,这可能会影响结果的速度(因为它对与myString 不匹配的每一行使用隐式打印),而不是使用更少的内存并打印所有行一次找到匹配。

【讨论】:

    【解决方案2】:

    简单的就是:

    /pattern/,/myString/s/myString/replacement_pattern/
    

    为了第一并且只有第一个文件中的 myString 我认为应该有一些简单的东西,但我最终得到:

    /pattern/,${ x; /myString/!{ x; //{ h; s//replacement_pattern/}; x}; x}'
    

    短一点:

    /pattern/,${ /myString/{ x; //!{ g; s//replacement_pattern/; x}; x} }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-06
      • 1970-01-01
      • 2011-10-27
      相关资源
      最近更新 更多