1

I have a xml tag like below:

<Setting Name="Check" Type="xsd:integer">53</Setting>

I need to fetch only 53 with the best possible code. Can someone suggest?

I know it can be achieved as below:

grep "Setting Name=\"Check\"" abc-test.xml | cut -d'>'  -f 2 |  cut -d'<' -f 1

Thanks

Skynet
  • 6,048
  • 5
  • 44
  • 49
Shankar Guru
  • 963
  • 1
  • 23
  • 42

3 Answers3

4

I will always suggest an xml parser for this kind of task, like and using xpath expressions. An example:

xmlstarlet sel -t -v '/Setting[@Name="Check"]/text()' abc-test.xml

that yields:

53

UPDATE with version:

xmllint --xpath '/Setting[@Name="Check"]/text()' abc-test.xml
Birei
  • 34,778
  • 2
  • 71
  • 80
  • But, xmlstarlet is not available on the linux host that am using at all.. Please let me know for any other way – Shankar Guru Feb 02 '15 at 13:48
  • You can also use `xmllint`, replacing the binary and its arguments but the xpath expression and the input file. But I'm not going to be trying until can find one of your toolbox. It's better you to visit this [how to parse xml from shell](http://stackoverflow.com/questions/4680143/how-to-parse-xml-using-shellscript) and choose one. – Birei Feb 02 '15 at 13:56
  • I see in my host --xpath for xmllint is not supported..I get the Usage listed Unknown option --xpath Usage : xmllint [options] XMLfiles ... – Shankar Guru Feb 02 '15 at 14:05
  • 2
    How to replace the value with something else with xmllint? – Khurshid Alam Nov 24 '16 at 04:27
3

Possible codes are as follows..I don't know if this is the "best" for you.

using sed

sed '/Setting Name="Check"/{s/^[^>]\+>\([0-9]\+\)<.*/\1/g}'

example

echo '<Setting Name="Check" Type="xsd:integer">53</Setting>'|sed '/Setting Name="Check"/{s/^[^>]\+>\([0-9]\+\)<.*/\1/g}'

using awk

   awk -v FS="<[^0-9]+>" '$0~"Setting Name=\"Check\""{print $2}'

example

echo '<Setting Name="Check" Type="xsd:integer">53</Setting>'|awk -v FS="<[^0-9]+>" '$0~"Setting Name=\"Check\""{print $2}'
repzero
  • 7,924
  • 2
  • 14
  • 38
2

With only grep command

grep -oP '(?<=>).*?(?=</Setting>)' input.xml

For extending conditions(i.e.: Check) you can mention elements too like this,

grep "Name=\"Check\"" input.xml|grep -oP '(?<=>).*?(?=</Setting>)' 

The output will be,

53

Here is what I tried,

enter image description here

Skynet
  • 6,048
  • 5
  • 44
  • 49