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
1  
-r seems to to that for me. – Torandi Jul 22 '09 at 23:46
1  
@jtbandes: You don't need the extended features for this expression.. I just requires 3 escape characters for ( ) + use \( \) \+: This is effectively the same: sed "s/.*'\([^']\+\)'.*/\1/" – Peter.O Jan 11 at 1:38
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.