1

I have the following XML file:

<?xml version="1.0" encoding="utf-8"?>
<deviceID>IO238470374109730497</devicdeID>
<KeyValuePairs>
    <KeyValuePair>
      <BASE-URL>2</BASE-URL>
      <Key>2</Key>
      <Value>2</Value>
    </KeyValuePair>
    <KeyValuePair>
     <BASE-URL>3</BASE-URL>
     <Key>3</Key>
     <Value>3</Value>
   </KeyValuePair>
</KeyValuePairs>

I want to delete only this section:

<KeyValuePair>
    <BASE-URL>3</BASE-URL>
    <Key>3</Key>
    <Value>3</Value>
</KeyValuePair>

What I want to achieve is to delete what is inside and including <KeyValuePair> only for these specific <BASE-URL>, <Key> and <Value>. The <KeyValuePair> tuple is always unique and won't be repeated, but it can be one or more.

How can I do that using bash?

0
4

Your example isn't a valid XML file. I've altered it slightly by adding a <root/> element surrounding the document (and fixing your typo in the closing </deviceID> marker):

<?xml version="1.0" encoding="utf-8"?>
<root>
    <deviceID>IO238470374109730497</deviceID>
    <KeyValuePairs>
        <KeyValuePair>
            <BASE-URL>2</BASE-URL>
            <Key>2</Key>
            <Value>2</Value>
        </KeyValuePair>
        <KeyValuePair>
            <BASE-URL>3</BASE-URL>
            <Key>3</Key>
            <Value>3</Value>
        </KeyValuePair>
    </KeyValuePairs>
</root>

Now it's possible to use an XML editing tool to edit your XML. This XPath expression tells xmlstarlet to delete the XML element <KeyValuePair/> (and its content) where <BASE-URL/> has a text value 3.

xmlstarlet ed -d '//KeyValuePair[BASE-URL/text()="3"]' /tmp/500185.xml

And the output is

<?xml version="1.0" encoding="utf-8"?>
<root>
  <deviceID>IO238470374109730497</deviceID>
  <KeyValuePairs>
    <KeyValuePair>
      <BASE-URL>2</BASE-URL>
      <Key>2</Key>
      <Value>2</Value>
    </KeyValuePair>
  </KeyValuePairs>
</root>
2
  • Thank you very much it works! How about doing this as a shell script? I also want to make another script to read the values in <Value> and call a curl command to their <BASE-URL> Feb 12 '19 at 19:37
  • xmlstarlet is a command you can call from a shell script, just like sed or awk or grep. There are lots of examples for xmlstarlet here on Unix & Linux and also on the other Stack Exchange sites. (I've written some of them.)
    – roaima
    Feb 12 '19 at 19:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.