-3

I have an xml file whose file structure is something like this

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <version>ABC</version>
    </parent>

    <version>XYZ</version>
</project>

I want to replace only the contents inside parent/version tag with the number 90 and not the contents of the version tag which is outside.

So basically my xml file should look like

    <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <version>90</version>
    </parent>

    <version>XYZ</version>
</project>

Note that contents inside parent/version tag should only be replaced not everything But when i use the below sed statement

sed -i "s/\(<version>\)[^<]*\(<\/version>\)/\190\2/" 

All the contents inside version attribute is replaced. The output is looking something like

    <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <version>90</version>
    </parent>

    <version>90</version>
</project>

which i don't want. How to achieve this

Abhishek
  • 650
  • 1
  • 8
  • 31
  • I suggest to use an XML/HTML parser (xmlstarlet, xmllint ...). – Cyrus May 31 '22 at 11:10
  • 1
    This is the same question you asked an hour earlier from a different login https://stackoverflow.com/q/72446046/1745001. Please don't post the same question multiple times, and please just use 1 login. – Ed Morton May 31 '22 at 14:29
  • Here's an example of how to do that with xmllint https://stackoverflow.com/a/69328235/2834978 – LMC May 31 '22 at 16:17

2 Answers2

0

Using sed

$ sed '0,/\(<version>\)[^<]*/{s//\190/}' input_file
<?xml version=1.0 encoding=UTF-8?>
<project xmlns=http://maven.apache.org/POM/4.0.0 xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance xsi:schemaLocation=http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd>
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <version>90</version>
    </parent>

    <version>XYZ</version>
</project>
HatLess
  • 10,622
  • 5
  • 14
  • 32
0

When you edit xml-files, it is best to make use of proper tools. For editing or querying xmlfiles, you can use xmlstarlet

$ xmlstarlet ed -u '//parent/version' -v "300" input_file.xml
kvantour
  • 25,269
  • 4
  • 47
  • 72