Issue
I have a pom file that has the following information:
<modelVersion>4.0.0</modelVersion>
<groupId>com.site.camera</groupId>
<artifactId>proj3</artifactId>
<packaging>pom</packaging>
<version>2.6</version>
<name>Proj 3</name>
I am writing a bash script and want to be able to open this file (pom.xml) and cut out the version (eg. 2.6 in this case). I am doing this because as I update the version I want the rest of my script to update with it.
Things that I have tried:
var=$(grep <version>2.6</version> pom.xml)
echo $var
Note that I have multiple version parameters in the pom file. And I need this specific version which is surrounded with this name, packaging, artifactId etc.
Solution
The simplest way is to use GNU grep's perl-compatible regexes
grep -oP '<version>\K[^<]+' pom.xml
With sed, you'd write
sed -n 's/^[[:blank:]]*<version>\([^<]\+\).*/\1/p' pom.xml
Thanks to David W.'s thoughtful commentary: the solution must use an XML parser. xmlstarlet
is one such tool:
ver=$( xmlstarlet sel -t -v /project/version pom.xml )
And just to be different, ruby comes with an XML parser in its standard library:
ruby -r rexml/document -e 'puts REXML::Document.new(File.new(ARGV.shift)).elements["/project/version"].text' pom.xml
Answered By - glenn jackman Answer Checked By - Gilberto Lyons (WPSolving Admin)