Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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>?

share|improve this question
up vote 5 down vote accepted

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.

share|improve this answer

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.

share|improve this answer
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>
share|improve this answer
    
this dosn't work (bash, debian wheezy) – rubo77 Jan 7 at 18:47

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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