如何在 Mac OS 上安装 GNU grep?

How to install GNU grep on Mac OS?

我需要在我的 Mac 上安装 GNU grep,但我遇到了一些困难。

我试过这样做:

brew install grep --with-default-names

但这不再是一个选项,因为 Homebrew 删除了 --with-default-names

任何人都可以为此提供解决方案吗?

是的,--with-default-namesremoved

但是一些公式,例如 grep,为此提供了解决方法:

$ brew info 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"
...

首先,要安装,只需执行 install 而无需 --with-default-names

$ brew install grep
...
==> Summary
  /usr/local/Cellar/grep/3.3: 21 files, 880.7KB

您还应该看到我在开头提到的相同“注意事项”信息。现在,默认情况下,Homebrew grep 将以“g”为前缀,因此它可以作为 ggrep.

访问
$ ggrep -V
ggrep (GNU grep) 3.3
Packaged by Homebrew
Copyright (C) 2018 Free Software Foundation, Inc.
...

这可以防止它隐藏 Mac 附带的内置 grep

$ grep -V
grep (BSD grep) 2.5.1-FreeBSD

如果你真的需要使用grep而不是ggrep,只需按照说明输入/usr/local/opt/grep/libexec/gnubin PATH 的开头。您必须在 .bashrc.bash_profile(无论您使用哪个)中执行此操作。

$ echo 'export PATH="/usr/local/opt/grep/libexec/gnubin:$PATH"' >> ~/.bash_profile
$ source ~/.bash_profile
$ grep -V
grep: warning: GREP_OPTIONS is deprecated; please use an alias or script
grep (GNU grep) 3.3
Packaged by Homebrew
...