Issue
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':
Solution
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.
Answered By - Wiktor Stribiżew