I have xml file where having tags <a>0000123</a>, <a>1200000</a>, <a>0001000</a>.

I need to get only the value which this particular tag should be between 100 to 1000.

  • tag will be in format of <a>0000123</a>
    – Ugan
    Feb 27 '18 at 13:32
  • So the tags are a tags (all a tags?) and their values is what you want to find? Do you want copies of those tags or do you just need the actual values?
    – Kusalananda
    Feb 27 '18 at 13:33
  • 1
    Please edit your question and add a xml example
    – ChristophS
    Feb 27 '18 at 13:36

Using XMLStarlet:

xml sel -t -v '//a[. > 100 and . < 1000]' -nl file.xml

This will return a list of values between 100 and 1000. These values will be taken from the values of the a nodes of the XML document in file.xml, regardless of where these appear. Zero-filled numbers seems to be handled properly. The -nl at the end ensures that the output's last line has a newline at the end.

On some systems, XMLStarlet is installed as xmlstarlet instead of just xml.


$ cat file.xml
<?xml version="1.0"?>

$ xml sel -t -v '//a[. > 100 and . < 1000]' -nl file.xml
  • In my case (kubuntu 17.10, bash) the command of the xmlstarlet package is xmlstarlet instead of xml. Works like a charme and does not look too complicated ;)
    – ChristophS
    Feb 27 '18 at 15:09

With :

xmllint --xpath '//a[text() > 100 and text() < 1000]/text()' file.xml

If you want to separate with newlines :

xmllint --shell file.xml <<< 'xpath //a[text() > 100 and text() < 000]/text()' |
    grep -oP 'content=\K.*'

AFAIK, it's a limitation of using xmllint without the switch --shell

  • How do you separate the result? for example by nl or whitespace ...
    – ChristophS
    Feb 27 '18 at 14:55
  • Check my edited post Feb 27 '18 at 15:01
  • 1
    As far as I could figure out, the output (without visual) separation is a correct xpath expression. A XSLT transformation could be the solution (compgroups.net/comp.text.xml/…). Great answer anyway!
    – ChristophS
    Feb 27 '18 at 15:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.