替换 shell 中的 XML 值

huangapple go评论62阅读模式
英文:

replace xml value in shell

问题

我想用sed替换XML文件中的一个值:
这是原始行:

<ns3:myID>aaa:bb:cc:dd::123-sd3-7b</ns3:myID>

我想替换&lt;ns3:myID&gt;&lt;/ns3:myID&gt;之间的值。

我尝试了

sed -Ei - "s/(myID&gt;).(<.)$/\1${MY_NEW_VALUE}\2/" path.xml

它确实替换了该值,但生成了一个新的临时文件,这是不可接受的,有人知道一个sed命令行,可以在不生成任何临时文件的情况下就地替换上述值吗?

英文:

I want to replace a value in XML file with sed:
here is the origin line:

&lt;ns3:myID&gt;aaa:bb:cc:dd::123-sd3-7b&lt;/ns3:myID&gt; 

I want to replace the values between &lt;ns3:myID&gt; and &lt;/ns3:myID&gt;.

I tried

sed -Ei - &quot;s/(myID\&gt;).*(&lt;.*)$/${MY_NEW_VALUE}/&quot; path.xml

it does replace the value, but it generates a new temp file which is not acceptable, can someone know a sed command line that can in-place replace the above value without generating any temp files?

答案1

得分: 1

像这样:


- `-L` 等同于 `sed` 的 `-i`
- 命名空间的 URL 就是你的 `xml` 文件中 `xmlns:ns3` 后面的内容。```

<details>
<summary>英文:</summary>

Like this:

    xmlstarlet edit -L -N ns3=&#39;&lt;NAMESPACE URL&gt;&#39; -u &#39;//ns3:myID&#39; -v NEW_VALUE file.xml

 - `-L` is equivalent to the `-i` of `sed`
 - the namespace URL is what is after `xmlns:ns3` in your `xml` file.

</details>



# 答案2
**得分**: 0

以下是翻译好的部分:

"Some implementations need an extension for `-i` (case for [FreeBSD](https://nixdoc.net/man-pages/FreeBSD/man1/sed.1.html) and MacOS, but not for [OpenBSD](https://man.openbsd.org/sed) and GNU/Linux.) This non standard option may also have some [subtle meaning](https://www.unix.com/man-page/FreeBSD/1/sed/). You should really check the documentation of the `sed` command you're using and be aware of portability issue of your script (if using it via a script)"

<details>
<summary>英文:</summary>

Some implementations need an extension for `-i` (case for [FreeBSD](https://nixdoc.net/man-pages/FreeBSD/man1/sed.1.html) and MacOS, but not for [OpenBSD](https://man.openbsd.org/sed) and GNU/Linux.) This non standard option may also have some [subtle meaning](https://www.unix.com/man-page/FreeBSD/1/sed/). You should really check the documentation of the `sed` command you&#39;re using and be aware of portability issue of your script (if using it via a script) 

</details>



huangapple
  • 本文由 发表于 2023年2月19日 04:05:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/75496081.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定