I am trying to find a way for grep to output only the content of a capturing group. For instance, if I have the following file:
hello1, please match me
hello2, please do not match me
I would like
grep -Eo '(hello[0-9]+), please match me' file
To output hello1
. However it outputs hello1, please match me
.
Now, I know that grep -Po 'hello[0-9]+(?=, please match me)'
will do the trick, but I'm thinking there must be a way to simply return a capturing group, but I couldn't find any info (on the net and in man grep
).
Is it possible, or are capturing groups only meant to be backrefenced ? It would seem weird to me if there was no way of doing that.
Thank you for your time, and feel free to critique the way this post is constructed!
GNU grep
doesn't support getting only the captured groups, unless you use lookarounds with PCRE option...ripgrep
(an alternate implementation) does support what you are asking, but in spirit that is more like the search and replacement functionality provided bysed
... so, if you need to manipulate capture groups,sed
would be better choice(?=)
group with-P
allows a sort of AND function in regexes. The other way to AND your regexes with grep is to pipe grep to grep. So what's wrong with piping grep to grep here?