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
3.8
5
# 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)"
Thank you!
5
0
4.16
7
# 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)"
Thank you!
7
0
Are there any code examples left?
New code examples in category Shell/Bash
-
Shell/Bash 2022-03-27 22:30:33 wise highlight ubuntu
-
Shell/Bash 2022-03-27 22:25:19 how to send a pull request in git
-
Shell/Bash 2022-03-27 21:55:06 how to open terminal in sublime text ubuntu
-
Shell/Bash 2022-03-27 21:25:19 how to switch branch
-
Shell/Bash 2022-03-27 21:20:25 python
-
Shell/Bash 2022-03-27 21:20:04 set user as admin gitlab
-
Shell/Bash 2022-03-27 21:10:09 apache2 mod_jk proxy to tomcat connector
-
Shell/Bash 2022-03-27 20:35:12 chown
-
Shell/Bash 2022-03-27 20:15:08 awk last match