How to install and use GNU Grep in macOS

Solution 1:

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.

Solution 2:

The answer from nohillside needs updating as follows:

If grep was already installed by brew, remove grep first.

% brew uninstall grep

Then install grep:

% brew install grep

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"
=º  /usr/local/Cellar/grep/3.3: 21 files, 880.7KB

Note that you do need to modify the PATH. For example, add to your .bashrc:

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

I had to do the above on my mac when after brew upgrade my grep was no longer accessible (it was installed previously with brew install grep --with-default-names, and this option is not available any more).

This solution works as of Homebrew 2.1.1:

brew --version
Homebrew 2.1.1
Homebrew/homebrew-core (git revision 5afdd; last commit 2019-04-22)
Homebrew/homebrew-cask (git revision a5a206; last commit 2019-04-22)

This answer is based on the one from nohillside, with comments from Jonathan Komar and scott m gardner.