Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"grep: invalid option -- P" error when doing regex in bash script

Tags:

grep

bash

macos

I am trying to use a regular expression in a bash script to retreive some text between "(" and ")" and I have this:

echo "device name, ID: (D96F7842-21D8-4E81-BAE6-DCF8EB66C734)" | grep -P '\((.*?)\)' 

After executing this in macOS terminal I get:

grep: invalid option -- P usage: grep
[-abcdDEFGHhIiJLlMmnOopqRSsUVvwXxZz] [-A num] [-B num] [-C[num]]  [-e
pattern] [-f file] [--binary-files=value] [--color=when]
  [--context[=num]] [--directories=action] [--label] [--line-buffered]
  [--null] [pattern] [file ...]

I searched for this error and read this thread but none of the solutions worked for me. Any ideas?

like image 693
Vladimir Amiorkov Avatar asked Aug 02 '26 06:08

Vladimir Amiorkov


1 Answers

Your grep command is using a PCRE .*? and so trying to use the GNU-only -P option to understand it but you're running on MacOS which uses a BSD version of grep. Just don't use a PCRE, use a BRE or ERE or similar or some other mechanism that'd let you use a mandatory POSIX tool which will work on every Unix box.

For example, using any awk

$ echo "device name, ID: (D96F7842-21D8-4E81-BAE6-DCF8EB66C734)" |
    awk -F'[()]' '{print $2}'
D96F7842-21D8-4E81-BAE6-DCF8EB66C734

or any sed:

$ echo "device name, ID: (D96F7842-21D8-4E81-BAE6-DCF8EB66C734)" |
    sed 's/.*(\([^)]*\).*/\1/'
D96F7842-21D8-4E81-BAE6-DCF8EB66C734

Regarding:

I searched for this error and read this thread

Upper/lower case matters in Unix commands, options, arguments, variables, etc. That thread is about lower case -p which is unrelated to the upper case -P option you were trying to use.

like image 173
Ed Morton Avatar answered Aug 05 '26 08:08

Ed Morton



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!