【问题标题】:Replace multiple lines using sed with other multiple lines使用 sed 将多行替换为其他多行
【发布时间】:2021-03-24 12:10:21
【问题描述】:

我试图找到这两行:

  <paramsToUseForLimit></paramsToUseForLimit>
</hudson.plugins.throttleconcurrents.ThrottleJobProperty>

并将它们替换为:

  <paramsToUseForLimit/>
</hudson.plugins.throttleconcurrents.ThrottleJobProperty>
<jenkins.branch.RateLimitBranchProperty_-JobPropertyImpl plugin="branch-api@2.6.3">
  <durationName>hour</durationName>
  <count>2</count>
  <userBoost>false</userBoost>
</jenkins.branch.RateLimitBranchProperty_-JobPropertyImpl>

来自我的文件 config.json

有人可以帮我用 sed 做到这一点吗?

sed -ie "s/那两行/替换为那 7 行/g" /config.json

【问题讨论】:

  • 感谢您在问题中表现出您的努力,但这并不清楚;您能否在您的问题中发布更清晰的输入和预期输出示例,以便更好地理解您的问题,谢谢。
  • @RavinderSingh13,我已经编辑了评论
  • This answer 应该让你走上正轨。
  • 不要使用sed解析xml文件。使用xmlstarlet 在xml 中插入数据。 sed 也适用于 lines。在sed 中进行多行重复是困难。它不是工作的工具
  • 我在这里找到了适合我的解决方案:stackoverflow.com/questions/23234681/…

标签: sed


【解决方案1】:

sed 可能不是完成这项任务的最佳工具。

sed -ie '/^  <\(paramsToUseForLimit>\)<\/\1/{
  N
  /\n<\/hudson.plugins.throttleconcurrents.ThrottleJobProperty>/{
    i \
  <paramsToUseForLimit/>\
</hudson.plugins.throttleconcurrents.ThrottleJobProperty>\
<jenkins.branch.RateLimitBranchProperty_-JobPropertyImpl plugin="branch-api@2.6.3">\
  <durationName>hour</durationName>\
  <count>2</count>\
  <userBoost>false</userBoost>\
</jenkins.branch.RateLimitBranchProperty_-JobPropertyImpl>
    d
  }
}' /config.json
  • /^.../{ - 如果模式空间匹配第一个匹配行:
    • N - 将下一行输入追加到模式空间
    • /\n.../{ - 如果模式空间匹配第二个匹配行:
      • i \ - 插入新文本(\ 嵌入换行符之前)
      • d- 删除原文,隐式打印,开始下一个循环
  • 否则,隐式打印(如果N 运行则为两行,否则为一行)
  • 开始下一个周期

这是相当脆弱的。例如,注意插入文本中的 shell 元字符。

【讨论】:

  • 也许c 超过i 命令?两者都必须使用反斜杠在换行符上继续输入,这表明使用r file 已经将替换行复制到第二个文件中,从而使用更少错误的技术。例如sed -e '/pattern/{r replacementFile' -e 'd}' inputFile
  • @potong 不错!这样干净多了。唯一的问题是pattern 是多行的,所以可能还需要换行。
【解决方案2】:

使用带有-z 选项的GNU sed 并受到Escape a string for a sed replace pattern 问答的启发 - 您可以正确地转义模式并将换行符替换为\ n 字符,然后传递给sed。那么就很简单了:

KEYWORD='  <paramsToUseForLimit></paramsToUseForLimit>
</hudson.plugins.throttleconcurrents.ThrottleJobProperty>'
REPLACE='  <paramsToUseForLimit/>
</hudson.plugins.throttleconcurrents.ThrottleJobProperty>
<jenkins.branch.RateLimitBranchProperty_-JobPropertyImpl plugin="branch-api@2.6.3">
  <durationName>hour</durationName>
  <count>2</count>
  <userBoost>false</userBoost>
</jenkins.branch.RateLimitBranchProperty_-JobPropertyImpl>'
ESCAPED_KEYWORD=$(printf '%s\n' "$KEYWORD" | sed -z 's/[]\/$*.^[]/\\&/g; s/\n/\\n/g');
ESCAPED_REPLACE=$(printf '%s\n' "$REPLACE" | sed -z 's/[\/&]/\\&/g; s/\n/\\n/g')
sed -z "s/$ESCAPED_KEYWORD/$ESCAPED_REPLACE/" input_file.txt

【讨论】:

    猜你喜欢
    • 2022-01-19
    • 1970-01-01
    • 2010-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-20
    相关资源
    最近更新 更多