【问题标题】:How to replace the 1st match block of text with sed?如何用 sed 替换第一个匹配文本块?
【发布时间】:2019-08-27 04:02:26
【问题描述】:

我正在尝试用 sed 替换第一个匹配文本块。 考虑这个例子。

read -r -d '' VAR <<"EOF"
<Button3d
some text
some text
/>

<Button3d
some text
some text
/>
EOF

sed '1,/^<Button3d/,/^\/>/c {
</Button\
different text\
different text\
/>\
}' <<< $VAR

但是使用 GNU sed 我得到以下错误:

sed:-e 表达式#1,字符 15:未知命令:`,'

预期的输出应该是:

<Button
different text
different text
/>

<Button3d
some text
some text
/>

有些人建议使用 XML 解析器,但对于这个简单的示例来说,这完全是多余的。

【问题讨论】:

  • 这看起来像 XML。您应该使用 XML 解析器。
  • 已更新。我不是在解析复杂的 XML。
  • @user11316197 在 sed 中使用正则表达式时,始终使用 sed 's+regex+new-text+g' file.txt 并仅在您想要替换所有出现时才使用 g,否则只需将其删除。 + 分隔符应与正则表达式一起使用,而不是 /

标签: bash shell unix sed sh


【解决方案1】:

当你的sed 支持-z 时,你可以使用类似的东西

sed -z 's#/>#\r#g; s/<Button3d[^\r]*\r//; s#\r#/>#g' <<< "${VAR}"

编辑: 可以插入其他文字

sed -z 's#/>#\r#g; s/<Button3d[^\r]*\r/<Button3d\nOther text\nSecond line\n\r/; s#\r#/>#g' <<< "${VAR}"

【讨论】:

  • 嗯。你用什么代替它??
  • 因为 '#&lt;Button3d.*/&gt;## 会尽可能多地替换,所以你需要一个技巧来告诉替换直到/&gt; 第一次出现。使用的技巧是首先将此字符串替换为唯一的单个字符(如 Windows 回车),然后将其他字符串替换并重新返回到 /&gt;
  • 这只是删除它。它必须用其他文本替换整个块。
  • 答案已编辑。使用带有替换字符串的 var 更复杂。
  • 第1、2、3场比赛号码在哪里指定??
猜你喜欢
  • 1970-01-01
  • 2018-12-18
  • 2010-09-13
  • 2020-04-27
  • 1970-01-01
  • 2012-02-27
  • 1970-01-01
相关资源
最近更新 更多