2 edited tags
| link
source | link

Can grep output only specified groupings that match?

Say I have a file:

# file: 'test.txt'
foobar bash 1
foobar happy

I only want to know what words appear after "foobar", so I can use this regex:

"foobar \(\w\+\)"

The parenthesis indicate that I have a special interest in the word right after foobar. But when I do a grep "foobar \(\w\+\)" test.txt, I get the entire lines that match the entire regex, rather than just "the word after foobar":

foobar bash 1
foobar happy

I would much prefer that the output of that command looked like this:


Is there a way to tell grep to only output the items that match the grouping (or a specific grouping) in a regular expression?