Take the 2-minute tour ×

I am working on a linux shell script to find information in a xml file using grep. I am on a mac which I hope doesn't matter too much.

To find the information I need, I run:

grep -oP "<title>(.*)</title>" temp.xml

I get in return a list of matches and this includes the <title> tag.

How can I get a list with only the information inside the title tag but without the title tag using grep?

share|improve this question
Why don't you use XPath instead? –  toniedzwiedz May 28 '12 at 9:02
It has to be a quick scripting job, I wouldn't like to spend ages on it. Can you recommend a good xpath command line tool? –  Filype May 28 '12 at 9:30
Looks like I've got xpath5.12 installed here already. No manual entry though –  Filype May 28 '12 at 9:32
Any of them will suffice. Your XPath would be as simple as possible '//title/text()' –  toniedzwiedz May 28 '12 at 9:33
Ture, I wasn't aware xpath was a command line tool. –  Filype May 28 '12 at 9:37

4 Answers 4

up vote 5 down vote accepted

I can't see why you'd want to use grep for this, while it can be solved with a trivial XPath expression:


There are many command line tools for XPath and they're usually bundled with the OS.

share|improve this answer
Examples of commands that support XPath are xgrep (wohlberg.net/public/software/xml/xgrep), xmlgrep (search.cpan.org/dist/XML-Twig/tools/xml_grep/xml_grep) or sgrep (cs.helsinki.fi/u/jjaakkol/sgrep.html). –  Claudix Sep 5 at 6:49

Since you already use grep -P, why don't you use its features?

grep -oP '(?<=<title>).*?(?=</title>)'

In the general case, XPath is the correct solution, but for toy scenarios, yes Virginia, it can be done.

share|improve this answer
but now grep -P is obsolete –  Bharat Jul 7 at 6:32
@Bharat Obsolete?? Can you provide a reference? –  tripleee Jul 7 at 7:48
i found that here –  Bharat Jul 7 at 7:55

It's not the best solution, I would search for XML lib in bash but you can do:

grep -oP "<title>(.*)</title>" temp.xml | cut -d ">" -f 2 | cut -d "<" -f 1
share|improve this answer
That's my solution for it too. –  Filype May 28 '12 at 9:29

You could install xgrep using xpath as suggested in Tom's answer

man xgrep

share|improve this answer

Your Answer


