4

Consider the following excerpt from a large XML file:

  ...
  <serverName someKey="false" anotherKey="0.05" thirdKey="0.04">
    <default>blah.blah.blah</default>
    <region name="US">us.blah.net</region>
    <region name="EU">eu.blah.net</region>
    <region name="IL">il.blah.net</region>
  </serverName>
  ...

How do I print the the lines between the opening tag <serverName ...> and the closing tag </serverName>?

5

sed is a great tool but XML will eventually make any programmer who approaches it with a REGEX cry. I know. I've been there. If there is even the smallest chance that your data will change, you want a proper XML parser.

My choice would be to use BeautifulSoup but it makes handling it directly from Bash fairly hard. If you want to write an intermediary Python script, that's still an option... Otherwise xpath is a fairly classic option. It's a wrapper around Perl's libxml library and it does some fairly powerful things.

sudo apt-get install libxml-xpath-perl

And for your example, here's how I'd do this in the xpath query language:

xpath -e '*/serverName/*' big_xml_file.xml

Again, if you need to do anything useful with this XML, consider something even stronger like BeautifulSoup and Python.

  • gives me error Cannot open file '-e' at /usr/share/perl5/vendor_perl/XML/XPath.pm line 53 – Manoj Feb 12 at 12:14
3
sed -n '/<serverName/,/<\/serverName/p' big_xml_file.xml

Did the trick (adapted from this post at linuxquestions.org).

On Ubuntu 14.04:

$ sed -n '/<serverName/,/<\/serverName/p' big.xml
<serverName someKey="false" anotherKey="0.05" thirdKey="0.04">
  <default>blah.blah.blah</default>
  <region name="US">us.blah.net</region>
  <region name="EU">eu.blah.net</region>
  <region name="IL">il.blah.net</region>
</serverName>
  • this dosn't work (bash, debian wheezy) – rubo77 Jan 7 '16 at 18:47
  • Works on ubuntu xenial. Can you explain, how? – Draco Ater Aug 24 '16 at 6:03
  • I think I got it. It's a range. From line matching pattern, to line matching pattern after ,. – Draco Ater Aug 24 '16 at 6:14
  • Problem: the matching is greedy. – Federico Oct 29 '17 at 17:33
  • It solved my problem too and thank you. Can you pls explain the pattern . – ArrchanaMohan Nov 14 '18 at 3:41
0

I can also imagine that you need to find a particular server from a longer list along with particular settings or regions based on some given conditional paths.

In that case, I would recommend wrapping your XPATH statements and conditions in an XSLT stylesheet. There are a number of XSLT parsers available in the repositories to work with the command line, PHP, Perl, Python, Java, etc.

XSLT is very powerful and can output text, xml, and html.

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.