up vote 12 down vote favorite
share [g+] share [fb]

Is it possible to use GNU grep to get a matched group from an expression?

Example:

echo "foo 'bar'" | grep -oE "'([^']+)'"

Which would output "'bar'". But I would like to get just "bar", without having to send it through grep one more time (ie. get the matched group). Is that possible?

link|improve this question
feedback

2 Answers

up vote 12 down vote accepted

You can use sed for this:

echo "foo 'bar'" | sed -E "s/.*'([^']+)'.*/\\1/"
link|improve this answer
Thanks, had forgotten about sed. But to clarify, sed doesn't take the argument -E.. – Torandi Jul 22 '09 at 23:36
Hm, it does on my machine (Mac OS X). Upon further examination, in the man page: "The -E, -a and -i options are non-standard FreeBSD extensions and may not be available on other operating systems." – jtbandes Jul 22 '09 at 23:40
Okay, it doesn't on mine (debian), what is -E supposed to do? – Torandi Jul 22 '09 at 23:42
It's similar to grep's -E: "Interpret regular expressions as extended (modern) regular expressions rather than basic regular expressions (BRE's). The re_format(7) manual page fully describes both formats." – jtbandes Jul 22 '09 at 23:44
1  
-r seems to to that for me. – Torandi Jul 22 '09 at 23:46
show 2 more comments
feedback

While grep can't output a specific group, you can use lookahead and behind assertions to achieve what your after:

echo "foo 'bar'" | grep -Po "(?<=')[^']+(?=')"

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.