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':
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With