如何在OSX中安装和使用GNU Grep


50

我有coreutils,但不确定是否有GNU grep。我只想使用-P在GNU grep中找到的Perl regex 标志,而不是在BSD grep中找到。

我的PATH是,/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因此我在PATH中首先拥有coreutils。

但是,当我使用grep时,它就是BSD:grep --versionGives grep (BSD grep) 2.5.1-FreeBSD

命令type -p grep返回/usr/bin/grep

如何在OSX中安装GNU Grep?

Answers:


72

GNU grep不是coreutils的一部分。要安装,请运行

brew install grep

与coreutils一样,这不会自动替换现有的grep

==> Caveats
The command has been installed with the prefix "g".
If you do not want the prefix, install using the "with-default-names" option.

2
当我这样做时,我grep仍然是freeBSD之一,但是egrepfgrep是GNU。如何将默认设置grep为GNU?(我确实使用过--with-default-names
多汁

3
@juicy您是否在新的shell中尝试了这个?
nohillside

3
作为参考,将GNU grep命令命名为ggrep
Will Sheppard,

2
运行brew uninstall grep(或brew remove grep)(如果已安装),并在命令行上brew install grep --with-default-names赋予GNU grep优先级。经过测试Homebrew 1.5.4 Homebrew/homebrew-core (git revision 3bb326; last commit 2018-02-22)不要忘了打开新的shell或运行hash -rexport PATH=$PATH重新加载二进制应用程序的路径(即新的GNU grep)。
乔纳森·科马尔

3
不幸的是,@ JonathanKomar在Homebrew 2.0.0版中--with-default-names标志不再可用。
Dez

5

如评论所示,最高评分的答案(从nohillside)需要更新如下:

如果brew已经安装了grep,请先删除grep。

% brew uninstall grep

然后安装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

请注意,您确实需要修改PATH。例如,添加到您的.bashrc中:

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

brew upgrade我无法再访问grep 之后(必须先使用进行安装brew install grep --with-default-names,并且该选项不再可用),我必须在mac上执行上述操作。

此解决方案自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)

该答案基于nohillside的答案,并附有Jonathan Komar和scott m gardner的评论。


这比公认的答案更好。
smci
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.