grep -P no longer works how can I rewrite my searc

2019-01-02 17:30发布

It looks like the new version of OSX no longer supports grep -P and as such has made some of my scripts stop working.

var1=`grep -o -P '(?<=<st:italic>).*(?=</italic>)' file.txt`

I need to capture the grep to a variable and I need to use the zero width assertions. as well as \K

var2=`grep -P -o '(property:)\K.*\d+(?=end)' file.txt`

Any alternatives would be greatly appreciated.

标签: macos perl shell
11条回答
还给你的自由
2楼-- · 2019-01-02 18:05

Another Perl solution for -P

var1=$( perl -ne 'print $1 if m#<st:italic>([^<]+)</st:italic># ' file.txt)
查看更多
裙下三千臣
3楼-- · 2019-01-02 18:08

There is another alternative: pcregrep.

Pcregrep is a grep with Perl-compatible regular expressions. It has the exactly same usage as grep -P. So it will be compatible with your scripts.

It can be installed with homebrew:

brew install pcre

查看更多
后来的你喜欢了谁
4楼-- · 2019-01-02 18:11

OS X tends to provide BSD rather than GNU tools. It does come with egrep however, which is probably all you need to perform regex searches.

example: egrep 'fo+b?r' foobarbaz.txt

A snippet from the OSX grep man page:

grep is used for simple patterns and basic regular expressions (BREs); egrep can handle extended regular expressions (EREs).

查看更多
弹指情弦暗扣
5楼-- · 2019-01-02 18:14

How about using the '-E' option? It works fine for me, for example, if I want to check for a php_zip, php_xml, php_gd2 extension from php -m I use:

php -m | grep -E '(zip|xml|gd2)'
查看更多
琉璃瓶的回忆
6楼-- · 2019-01-02 18:18

If your scripts are for your use only, you can install grep from homebrew-core using brew:

brew install grep --with-default-names

When you specify --with-default-names, it replaces the system grep (actually, puts the installed grep before the system one on the PATH).

The version installed by brew includes the -P option, so you don't need to change your scripts.

If you install without --with-default-names, then it's available as ggrep (GNU grep).

查看更多
无与为乐者.
7楼-- · 2019-01-02 18:18

Install ack and use it instead. Ack is a grep replacement written in Perl. It has full support for Perl regular expressions.

查看更多
登录 后发表回答