macos - 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?
解决方案
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
推荐阅读
- php - 如何使用 PHP 打印这个数字序列?
- python - 如何保存连体模型的基础网络?
- php - 将产品简短描述添加到 WooCommerce 电子邮件通知
- python - Heroku 计划的 Python 脚本每隔几天就会崩溃一次
- react-native - React 检测到 StackNavigator 调用的 Hook 顺序发生了变化
- python - 如何创建 0 维 tf.Variable?
- php - 如何在 SQL 中自动填充多对多表
- html - 如何删除导航栏中按钮的悬停行为?
- php - Laravel 重定向未经授权的操作
- python - 在python中预测kNN中的浮点值时出错