By using grep I only want those lines out of all xml files that contains <active>true</active> tags and the next line after that should be <codePool>community</codePool>.

A sample XML file would be like below:

<?xml version="1.0"?>
                <Company_Module2 />

But there are many like this files in the folder, the XML structure is same.

My current grep command is:

grep -rl '<active>true</active>' --include='*.xml' --color=always

How can I achieve this in command line searching ?

  • 1
  • With some sample XML, I can give you a better answer. grep is not the right tool for this job - XML is not a regular language.
    – Sobrique
    Nov 18 '16 at 16:38
  • @Sobrique well my need is to do this in SSH Remote Terminal, where I cannot install any third party XML command line tool, so can you suggest how to do this with sed ?
    – Vicky Dev
    Nov 18 '16 at 20:31
  • @VickyDev Installing a proper XML parsing tool like XMLStarlet is always possible. Have a talk with the admin about it, or install it in your home directory. You can run most parts of a Unix system from a home directory.
    – Kusalananda
    Jan 5 '17 at 16:16

Assuming all XML files are in the current directory and matches the pattern *.xml, and that it's the filenames that you want of the files that contains the specified XML:

$ xml sel -t -i '/config/modules/Company_Module[active = "true" and codePool = "community"]' -f -nl ./*.xml

This uses XMLStarlet (xml, but sometimes installed as xmlstarlet) which is a command line XML parsing tool.

It tries to match the specified XPath expression and, if it matches, outputs the filename of the input file that contained the matching XML.

Since it's using an XML parser, it's independent of the ordering of the tags within the <Company_Module> node.

  • cool. In my Linux machine the command is installed under the name of xmlstarlet sel -t -i ....
    – JJoao
    Jan 5 '17 at 13:48

Well I didn't want to leave grep command which I have used for so long.

So I found a way to do that with just below thingy:

grep -rzl '<active>true</active>.*<codePool>community</codePool>' --include='*.xml' --color=always

This worked fine for me.

grep -A1 "<active>" *.xml

A1 -> print the pattern and next line.

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.