I have a collection of XML files in a standard format that I'd like to search to see if they match two strings.

Here is the idea:


How can I match the content of ELEMENT1 and ELEMENT2 with egrep and return the filename that contains them?

  • You should first read this to realize how bad it is to use regexps to parse HTML or XML : stackoverflow.com/questions/1732348/…. To look for an element in a XML file, use an XPath expression instead. – lgeorget Mar 7 '14 at 12:43
  • Shouldn't it be </ELEMENT1> instead of </ELEMENT> above? – Stéphane Chazelas Mar 7 '14 at 12:48

With recent GNU grep built with recent PCRE:

grep -Po '<(ELEMENT[12]>)\K.*?(?=</\1)'
| improve this answer | |

The following XQuery should give you the desired output :

for $x in (/content/element1,/content/element2)
return $x/text()

For example, with an XQuery interpreter such as XQilla and an input file like

<?xml version="1.0" ?>

xqilla -i 1.xml 1.query outputs


For your example, regexps might be sufficient but in the general case it's a bad idea to use them for XML parsing because XML is not a regular language (i.e. a language parsable with regular expressions).

| improve this answer | |

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.