Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grep -P no longer works. How can I rewrite my searches?

Tags:

shell

macos

perl

It looks like the new version of OSX no longer supports grep -P and as such has made some of my scripts stop working.

var1=`grep -o -P '(?<=<st:italic>).*(?=</italic>)' file.txt` 

I need to capture the grep to a variable and I need to use the zero width assertions, as well as \K

var2=`grep -P -o '(property:)\K.*\d+(?=end)' file.txt` 

Any alternatives would be greatly appreciated.

like image 313
kugyousha Avatar asked May 20 '13 20:05

kugyousha


People also ask

How do you force grep?

To force GNU grep to output lines even from files that appear to be binary, use the -a or ' --binary-files=text ' option. To eliminate the “Binary file matches” messages, use the -I or ' --binary-files=without-match ' option, or the -s or --no-messages option. Why doesn't ' grep -lv ' print non-matching file names?

How do I stop grep search?

While executing a bash script it stalls on a grep command. The Terminal just stops doing anything and you have press CTRL+Z to stop the script.

What does grep return if it doesn't find anything?

The grep manual at the exit status section report: EXIT STATUS The exit status is 0 if selected lines are found, and 1 if not found. If an error occurred the exit status is 2.

How do I stop grep after first match?

The grep command has an -m or --max-count parameter, which can solve this problem, but it might not work like you'd expect. This parameter will make grep stop matching after finding N matching lines, which works great as it will limit the output to one line, always containing the first match.


1 Answers

If your scripts are for your use only, you can install grep from homebrew-core using brew:

brew install grep  

Then it's available as ggrep (GNU grep). it doesn't replaces the system grep (you need to put the installed grep before the system one on the PATH).

The version installed by brew includes the -P option, so you don't need to change your scripts.

If you need to use these commands with their normal names, you can add a "gnubin" directory to your PATH from your bashrc like:

PATH="/usr/local/opt/grep/libexec/gnubin:$PATH" 

You can export this line on your ~/.bashrc or ~/.zshrc to keep it for new sessions.

Please see here for a discussion of the pro-s and cons of the old --with-default-names option and it's (recent) removal.

like image 178
drevicko Avatar answered Sep 23 '22 12:09

drevicko