Search code examples
bashmacosgrep

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


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?


Solution

  • 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.