Tuesday, March 15, 2022

[SOLVED] How to treat files as huge string with macos grep?

Issue

I'm using the following command on Ubuntu to list all files containing a given pattern:

for f in *; do if grep -zoPq "foo\nbar" $f; then echo $f; fi; done

But on macos, I'm geting the following error:

grep: invalid option -- z

There's no -z option to treat files as a big string with macos grep, unlike gnu grep.

Is there another option on macos grep equivalent to `-z ? If not, what alternative can I use to get the same result ?


Solution

You can install pcregrep via home brew, and then use it with the -M option:

By default, each line that matches a pattern is copied to the standard output, and if there is more than one file, the file name is output at the start of each line, followed by a colon. However, there are options that can change how pcregrep behaves. In particular, the -M option makes it possible to search for patterns that span line boundaries. What defines a line boundary is controlled by the -N (--newline) option.



Answered By - Wiktor Stribiżew
Answer Checked By - Timothy Miller (WPSolving Admin)