Home » Questions » Computers [ Ask a new question ]

Can GNU Grep output a selected group?

Can GNU Grep output a selected group?

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

Asked by: Guest | Views: 199
Total answers/comments: 2
Guest [Entry]

"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"""
Guest [Entry]

"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."