Jasmine Lognnes Jasmine Lognnes - 1 year ago 51
Perl Question

Can grep print just the matched buffer?

If I do

# perl -lne "print \$1 if /'?(\d{5})'?:/" courses.yaml

then I get the result I want, but now I want to do it with

Why doesn't the following get me the same output?

# grep -oP "\'?(\d{5})\'?:" courses.yaml

Answer Source

You print Group 1 contents in the first case, and the whole match in the second. When using grep with -oP, you can only print the whole match, thus, use a (?='?:) lookahead that will only return a 5-digit chunk if there is a : after them preceded with an optional single quote:

echo "'00000':  '01005':" | grep -Po "\d{5}(?='?:)"

See demo

I think there is no point in using a lookbehind here since the ' is optional in your pattern.