0

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

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

I want to replace the values between <ns3:myID> and </ns3:myID>.

I tried

sed -Ei - "s/(myID\>).*(<.*)$/\1${MY_NEW_VALUE}\2/" 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?

Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
lalala
  • 1
  • 1
  • Show us your XML input. – Gilles Quénot Feb 18 '23 at 20:09
  • 4
    [Don't use `sed` nor `regex` to parse `XML`](https://stackoverflow.com/a/49352373/465183) you cannot, must not parse any structured text like XML/HTML with tools designed to process raw text lines. If you need to process XML/HTML, use an XML/HTML parser. A great majority of languages have built-in support for parsing XML and there are dedicated tools like XMLStarlet if you need a quick shot from a command line shell. Never accept a job if you don't have access to proper tools. – Gilles Quénot Feb 18 '23 at 20:09
  • Can you try removing the `hyphen` after the `-Ei` ? – hacker315 Feb 19 '23 at 11:46
  • I tried but got an error. – lalala Feb 20 '23 at 20:37

2 Answers2

1

Like this:

xmlstarlet edit -L -N ns3='<NAMESPACE URL>' -u '//ns3:myID' -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.
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
0

Some implementations need an extension for -i (case for FreeBSD and MacOS, but not for OpenBSD and GNU/Linux.) This non standard option may also have some subtle meaning. 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)

gildux
  • 448
  • 6
  • 12