首页 > 解决方案 > 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

标签: regexsedpattern-matching

解决方案


这可能对您有用(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)。?+{...}


推荐阅读