0

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.

1
  • only when the artifactId is app1 as we would be having the multiple same set of tags so write code for that. You can use Python or Perl xml modules, there is xmllint and xmlstarlet. Shell has no XML support. Commented Feb 22, 2022 at 15:05

2 Answers 2

2

For parsing xml files use xml parsers.

xmllint --xpath 'string(//version)' -
Sign up to request clarification or add additional context in comments.

1 Comment

Or perhaps //*[artifactId="app1"]/version since the requirement was only when the artifactId is app1.
0

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

2 Comments

The whole code (the fishing rod, the mealworm and even the fish) : version=$( cat $file | egrep ''<version>' | cut '> -f 2 | cut '<' -f 1 | tail -n 1 ) ; echo "version=${version}" Do not forget the "tail", to ensure you only have one result, the first one, in case of multiple values (standard failure case that may be catastrophic in some situations)
Thanks @Gaetan, I tried the above as script file and getting given error. #!/bin/bash file=/tmp/path/my.xml echo $file version=$( cat $file | egrep ''<version>' | cut '> -f 2 | cut '<' -f 1 | tail -n 1 ) ; echo "version=${version}" However this is failing with below error. /tmp/path/my.xml ./test1.sh: line 4: version: No such file or directory cut: '<': No such file or directory version=

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.