grep capture group code example
Example 1: grep print only capture group
## Short answer:
$ grep -oP 'stuff before your match\Kyour match(?=stuff after your match)'
## Explanation:
# GNU grep has the -P option for perl-style regexes, and the -o option to print
# only what matches the pattern.
# These can be combined by using perl-style look-around assertions (described
# under Extended Patterns in the perlre manpage) to not count the beginning and
# end of the regex as part of the match that -o will grab.
# Prefix your match pattern with \K to exclude the beginning. \K is the shorter
# (and more efficient) form of (?<=pattern), a zero-width look-behind assertion
# that means, "Matches must come after this."
# Put anything following your match pattern within (?=pattern). This is a zero-
# width look-ahead assertion that means, "Matches must be followed by this."
# set up a test file for reference
$ echo '
foobar bash 1
bash
foobar happy
foobar
foo bar
foo 123 bar
foo abc bar
' > test.txt
$ grep -oP 'foobar \K\w+' test.txt
# bash
# happy
$ grep -oP 'foo \K\w+(?= bar)' test.txt
# 123
# abc
Example 2: grep capture group
# matches and returns b
$ echo "abc" | grep -oP "a\K(b)(?=c)"
b
# no match
$ echo "abc" | grep -oP "z\K(b)(?=c)"
# no match
$ echo "abc" | grep -oP "a\K(b)(?=d)"