首页 > 解决方案 > BSD grep "?" wildcard alternative for GNU

问题描述

I have a grep command that works on my Mac with BSD grep 2.5.1-FreeBSD which I'm using to search a very long, single-line bash var:

echo $MY_VAR | grep -Eo s3.+?model

On Ubuntu with GNU grep 2.25, the ? wildcard doesn't seem to work. It doesn't stop at the first occurrence of "model".

Would someone please show me how to get this same match in Ubuntu? Open to either changing the pattern or installing a different/updated grep.

Not going to list the million patterns I've tried so far, but been struggling for a while with this.

Edit: The following seems to work since there's a "," after "model", but looks pretty ugly:

egrep -o 's3.*model' | grep -o '^[^,]*'

Is there a better way?

标签: macosubuntugrep

解决方案


You may use a PCRE regex option P with GNU grep, it also allows the use of non-greedy quantifiers:

echo $MY_VAR | grep -Po s3.+?model
                     ^

See the online demo:

MY_VAR="s3://model/;s3://another/model"
echo $MY_VAR | grep -Po 's3.+?model'
# => s3://model
#    s3://another/model

推荐阅读