regex - sed 重复匹配行为不端
问题描述
我正在尝试从以下字符串获取文件路径:
"# configuration file /etc/nginx/conf.d/default.conf"
通过将其传递给sed
:
sed -n 's,\(# configuration file \)\(\/[a-zA-Z_.]\+\)\+,\1,'
我希望/etc/nginx/conf.d/default.conf
被抓住\1
,但令人惊讶的是只有default.conf
部分被退回。在这里,我了解到每次下一次匹配时都会重新填充引用的部分/[a-zA-Z_.]\+
。每个下一个匹配项都转到下一个引用是否符合逻辑,所以default.conf
将在 中返回\4
?
/[a-zA-Z_.]\+ >>>
\(/etc\)\(/nginx\)\(/conf.d\)\(/default.conf\)
\1 \2 \3 \4
解决方案
这可能对您有用(GNU sed):
sed -nE 's,(# configuration file )((/[a-zA-Z_.]+)+),\2,p' file
这将捕获文件路径。
sed -nE 's,(# configuration file )((/[a-zA-Z_.]+)+),\1,p' file
这将捕获评论的开头。
sed -nE 's/(# configuration file )((\/[a-zA-Z_.]+)+)/\3/p' file
这将捕获文件路径的结尾。
注意当一个捕获组被某个可能重复的东西限定时,即,*
或它之间的任何东西将保留最后一次这样的重复(参见解决方案 3)。?
+
{...}
推荐阅读
- ssis - SSIS派生列表达式将特定字符移动到字符串的末尾
- javascript - 用逗号或冒号分割字符串
- visual-studio-2017 - 什么时候用哪个更合适?MsVS 2017 重建还是构建?
- python - 加载图然后用它来构建 tflite?
- python-3.x - xgettext 不只从特定目录中获取字符串
- delphi - Delphi 无法从 VertScrollBox 中删除子级
- kubernetes - Kubernetes Dashboard 静态密码文件无法列出
- r - 确定匿名函数中函数的命名空间
- android - 无法在 Android Studio 中访问 Context.BAKUP_SERVICE
- r - 处理 .csv 文件中的 NA 值