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 &quot;abc&quot; | grep -oP &quot;a\K(b)(?=c)&quot; 
b 
# no match
$ echo &quot;abc&quot; | grep -oP &quot;z\K(b)(?=c)&quot;
# no match
$ echo &quot;abc&quot; | grep -oP &quot;a\K(b)(?=d)&quot;

3.8 (5 Votes)
0
4.16
7
Jwarren 90 points

                                    # matches and returns b
$ echo &quot;abc&quot; | grep -oP &quot;a\K(b)(?=c)&quot; 
b 
# no match
$ echo &quot;abc&quot; | grep -oP &quot;z\K(b)(?=c)&quot;
# no match
$ echo &quot;abc&quot; | grep -oP &quot;a\K(b)(?=d)&quot;

4.16 (19 Votes)
0
Are there any code examples left?
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source