Does grep work differently on OSX [closed]

2020-02-09 02:19发布

问题:


Want to improve this question? Update the question so it's on-topic for Stack Overflow.

Closed 6 years ago.

I am trying to use grep like I am used to from Linux, with all its amazing features and all the power from RegEx,... but on Mac OS X it's not working as I expect.

If I use "-P" (Perl Regex) it gives me the "usage" (--help) output. In there we find the "-P" parameter in the list of parameters "-abcDEFGHhIiJLlmnOoPqRSsUVvwxZ"... Still not working.

Another example is the asterisk or the plus sign. I am trying this http://wiki.bash-hackers.org/howto/conffile

To check a config file for inappropriate content that instruction uses:

if egrep -q -v '^#|^[^ ]*=[^;]*' "$configfile"; then
  echo "Config file is unclean, cleaning it..." >&2
  # filter the original to a new file
  egrep '^#|^[^ ]*=[^;&]*'  "$configfile" > "$configfile_secured"
  configfile="$configfile_secured"
fi

And it does not work on lines like this:

DATABASE=some_database; ls -la

What am I doing wrong? Cause all of this works just fine on Linux machines.

回答1:

ubuntu (well, my ancient ubuntu 8 box I'm sitting beside…):

$ grep -V
GNU grep 2.5.3

OS X:

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

Yeah; they're different programs. OS X is not Linux. It's based on BSD.

If you want the GNU version of grep, with its various extensions, you can install it easily with Homebrew.



回答2:

On OS X you have FreeBSD grep by default, on Linux usually GNU grep.

The following resources may explain why GNU grep seems to be better (and faster):

  • why GNU grep is fast (by GNU grep's original author)
  • BSD grep on the FreeBSD Wiki
  • GNU grep is 10x faster than Mac grep


回答3:

Mac OS X is based on BSD, and does not use the GNU tools you are used to. I'd read up on POSIX grep because without GNU extensions you'll keep getting agitated for no reason. Everything should still be possible, just not in the exact way you're used to.