Search code examples
unixxpathpom.xmlxmllint

Unable to get version using artifactId from pom file


I am fairly new to unix shell scripting. Trying to capture version info of some artifact from xpom.xml without success.

I can't install anything extra in the system, checked that xmllint is installed. Any solution using either direct unix command or xmllint is appreciated.


file =~/xpom.xml

<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 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.generic</groupId>
  <artifactId>genericlist</artifactId>
  <packaging>pom</packaging>
  <version>10.0.25</version>
  <name>GenericRelease12.x.3</name>
  <description>GenericRelRepo</description> 
  <dependencies>  
    <dependency>
        <groupId>org.alpha</groupId>
        <artifactId>alpha</artifactId>
        <version>1.1.1</version>
        <type>war</type>
    </dependency>
    <dependency>
        <groupId>com.db</groupId>
        <artifactId>oradatabase</artifactId>
        <version>7.7.7</version>
        <type>jar</type>
    </dependency>
  </dependencies> 
</project>

I need to capture version of oradatabase artifactId. Solution should return 7.7.7.

I tried following without any success (got these tips from this site and modified it to meet my need:

attempt 1:

xmllint --xpath '//project/dependencies/dependency[artifactId='oradatabase']/@value' xpom.xml

it throws Unknown option --xpath

attempt 2:

artifactId=$(xmllint --format --shell "$file" <<< "cat //project/dependencies/dependency/artifactId/text()" | grep -v /)
if [[ $artifactId =~ ^(oradatabase)$ ]]
then
    version=$(xmllint --format --shell "$file" <<< "cat //project/dependencies/dependency/artifactId/text()" | grep -v /)
    echo "version is: " ${version}
else
    echo "Not found"
fi

-- returns Not found.

Thanks for any help on this.


Solution

  • You can try this:

    grep -A 1 oradatabase pom.xml | sed -nr 's|.*<version>(.*)</version>.*|\1|p'

    grep -A 1 oradatabase finds the line with oradatabase and prints also one line after it (context after). Then sed simply extracts the version number.