PS83
PS83

Reputation: 69

Extract an XML element value in shell script

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.

Upvotes: 0

Views: 1211

Answers (2)

KamilCuk
KamilCuk

Reputation: 140880

For parsing xml files use xml parsers.

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

Upvotes: 2

Ga&#233;tan RYCKEBOER
Ga&#233;tan RYCKEBOER

Reputation: 304

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

Upvotes: 0

Related Questions