Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shellscript Read XML attribute value

Tags:

bash

shell

sed

awk

We want to read XML attributes from an XML file. Example of file content is as below:

<properties>
  <property name="abc" value="15"/>
  <property name="xyz" value="26"/>
</properties>

We want to read value (i.e. 15) for property "abc" using shell script.
Please suggest shell commands to achieve this.

like image 313
patel kavit Avatar asked Aug 26 '14 14:08

patel kavit


2 Answers

You can use a proper XML parser like xmllint. If your version supports xpath, it will be very easy to grab specific values. If it doesn't support xpath, then you can use --shell option like so:

$ echo 'cat //properties/property[@name="abc"]/@value' | xmllint --shell myxml
/ >  -------
 value="15"
/ > 

You can then use awk or sed to format and extract desired field from output.

$ echo 'cat //properties/property[@name="abc"]/@value' | xmllint --shell myxmlfile | awk -F'[="]' '!/>/{print $(NF-1)}'
15

You can use command substitution to capture the output in a variable by saying:

$ myvar=$(echo 'cat //properties/property[@name="abc"]/@value' | xmllint --shell myxml | awk -F'[="]' '!/>/{print $(NF-1)}')
$ echo "$myvar"
15

Using anything else other than a xmlparser is prone to errors and will break easy.

like image 83
jaypal singh Avatar answered Sep 22 '22 01:09

jaypal singh


quick and dirty

sed -n '/<Properties>/,\|</properties>| {
   s/ *<property name="xyz" value="\([^"]*\)"\/>/\1/p
   }'

no xml check and based on your sample so assume same structure (one property name per line, ...)

posix version (--posix for GNU sed)

like image 20
NeronLeVelu Avatar answered Sep 21 '22 01:09

NeronLeVelu