Home > Software engineering >  Extract an XML element value in shell script
Extract an XML element value in shell script

Time:02-23

I have something like below in my sample.xml file, and want to extract the value which is in version tag only when the artifactId is app1 as we would be having the multiple same set of tags with different artifactId in the given file using shell script.

<groupId>abc.app1</groupId>
<artifactId>app1</artifactId>
<packaging>pom</packaging>
<name>app1 ${version}</name>
<version>1.2.50</version>

My final output would be like below,

variable1=1.2.50

Note that I need to read a file and extract that string.

CodePudding user response:

Be carefull of XML pattern extract. It may become odd if the pattern is a hierarchy, and you may have to use XML dedicated libraries.

But, in your example, you may use a combination of grep and cut to extract your pattern:

cat $file | egrep '<version>' \
| cut '> -f 2 | cut '<' -f 1

CodePudding user response:

For parsing xml files use xml parsers.

xmllint --xpath 'string(//version)' -
  • Related