Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can grep print just the matched buffer?

If I do

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

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

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

# grep -oP "\'?(\d{5})\'?:" courses.yaml 
'00000':
'01005':
like image 403
Jasmine Lognnes Avatar asked Mar 06 '26 20:03

Jasmine Lognnes


1 Answers

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.

like image 66
Wiktor Stribiżew Avatar answered Mar 09 '26 12:03

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!