81

I have coreutils but I am not sure if GNU grep is there. I just want to use the flag -P for Perl regex that is found in GNU grep, but not in BSD grep.

My PATH is /usr/local/opt/coreutils/libexec/gnubin:/usr/local/bin:/usr/bin:/opt/local/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin:/usr/local/git/bin:/usr/texbin:/Users/masi/.cabal/bin so I have coreutils first in the PATH.

However, grep is BSD when I am using it: grep --version gives grep (BSD grep) 2.5.1-FreeBSD.

Command type -p grep returns /usr/bin/grep

How can you install GNU Grep in macOS?

0

2 Answers 2

121

GNU grep is not part of coreutils. To install, run

brew install grep

As with coreutils, this doesn't automatically replace the existing grep

==> Caveats
All commands have been installed with the prefix "g".
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"

So after installing you can either use ggrep, gegrep and gfgrep; or extend PATH as shown above to use grep etc. The second option may confuse some macOS specific scripts though in case the options differ.

PS: On Apple Silicon, use

PATH="/opt/homebrew/opt/grep/libexec/gnubin:$PATH"

to amend the path.

1
  • 2
    Run brew uninstall grep (or brew remove grep) if installed already and brew install grep --with-default-names to give GNU grep precedence on the command line. Tested with Homebrew 1.5.4 Homebrew/homebrew-core (git revision 3bb326; last commit 2018-02-22) Do not forget to open a new shell or run hash -r or export PATH=$PATH to reload the paths to binary applications (i.e. your new GNU grep). Commented Feb 22, 2018 at 8:51
0

nohillside has the right idea. To extend it because the answer did not work for my case. The answer really depends on your local Homebrew setup.

Here is what I do to achieve a full replacement of the macOS/Darwin binaries (executables + man pages):

# grep without g-prefix
export PATH="/opt/homebrew/opt/grep/libexec/gnubin:$PATH"
export MANPATH="/opt/homebrew/opt/grep/libexec/gnuman:$MANPATH"

The trick is to find the libexec directory for the binaries you need in your homebrew installation directory. Have a look at their structure because the structure depends on the pacakge e.g. Python 3.10 -> /opt/homebrew/opt/[email protected]/libexec/bin.

Do not forgot to start a new shell before trying out your changes!

1
  • It basically depends on having an Intel vs an Apple Silicon Mac. When I wrote that answer, Apple Silicon was still a well-kept secret. Commented Jan 10, 2025 at 12:02

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.