Can GNU Grep output a selected group?
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?
You can use sed
for this. On BSD sed
:
echo "foo 'bar'" | sed -E "s/.*'([^']+)'.*/\\1/"
Or, without the -E
option:
sed "s/.*'\([^']\+\)'.*/\1/"
This doesn't work for multiline input. For that you need:
sed -n "s/.*'\([^']\+\)'.*/\1/p"
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 "(?<=')[^']+(?=')"
You can use \K
to reset and discard the left hand match text along with a lookahead which is not added to the match text:
$ echo "foo 'bar'" | grep -oP "'\K[^']+(?=')"
bar
GNU grep only.