1

I am using an XML that has definitions in this form -

<definition name="ticketOpen" extends="ticketUpdate">
    <put name="title" value="Open Ticket" />
    <put name="mainForm" value="open.jsp" />
    <put name="XYZ" value="PQR" />
            ...
</definition>

If I want to search for the definition of "ticketOpen", I can use grep like this -

grep "definition *name *= *\"ticketOpen\"" definitions.xml

However, this only returns the first line of the definition. How can I specify that after finding the first matching line, grep (or any other utility) should then look for the closing tag </definition> and print all those lines in between them?

  • 2
    Use a XML parser. You might want to look at xmllint. – devnull Feb 14 '14 at 15:35
2

Use sed:

sed -n -e '/definition/,/\/definition/ p' definitions.xml
2

The xml2 command will convert XML to flat text.

$ cat foo.xml 
<?xml version='1.0'?>
<doc name="document">
<object name="foo">
<key name="bar">baz</key>
</object>
<definition name="ticketOpen" extends="ticketUpdate">
<put name="title" value="Open Ticket" />
<put name="mainForm" value="open.jsp" />
<put name="XYZ" value="PQR" />
</definition>
</doc>
$ xml2 < foo.xml 
/doc/@name=document
/doc/object/@name=foo
/doc/object/key/@name=bar
/doc/object/key=baz
/doc/definition/@name=ticketOpen
/doc/definition/@extends=ticketUpdate
/doc/definition/put/@name=title
/doc/definition/put/@value=Open Ticket
/doc/definition/put
/doc/definition/put/@name=mainForm
/doc/definition/put/@value=open.jsp
/doc/definition/put
/doc/definition/put/@name=XYZ
/doc/definition/put/@value=PQR

I don't know what the rest of your XML document looks like, but assuming this is the only instance of definition you can directly grep for it.

1

Seems like this is something that would be more appropriate to use xpath. If that is an option, I can get up a sample command line.

This command is available in ubuntu from the package libxml-xpath-perl.

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.