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
CodePudding user response:
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>
CodePudding user response:
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