Extract only groups with grep regex, regular expression

Input:
foobar bash 1
foobar happy
Extract the word after "foobar ":
grep -oP 'foobar \K\w+' test.txt
The \K is the short-form (and more efficient form) of (?<=pattern) which you use as a zero-width look-behind assertion before the text you want to output. (?=pattern) can be used as a zero-width look-ahead assertion after the text you want to output.

For instance, if you wanted to match the word between foo and bar, you could use:
grep -oP 'foo \K\w+(?= bar)' test.txt
or (for symmetry):
grep -oP '(?<=foo )\w+(?= bar)' test.txt

No comments: