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

Consider the following excerpt from a large XML file:

  <serverName someKey="false" anotherKey="0.05" thirdKey="0.04">
    <region name="US"></region>
    <region name="EU"></region>
    <region name="IL"></region>

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

share|improve this question

3 Answers 3

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
sed -n '/<serverName/,/<\/serverName/p' big_xml_file.xml

Did the trick (adapted from this post at

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

Your Answer


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.