【发布时间】: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,否则只需将其删除。+分隔符应与正则表达式一起使用,而不是/。