Warm tip: This article is reproduced from serverfault.com, please click

shell-Bash grep不返回第一个正则表达式匹配项

(shell - Bash grep doesn't return the first regex match)

发布于 2020-12-02 08:45:13

所以我有这样的shell脚本:

echo "stackoverflow.com:1111/?a=b&c=d" | grep -o "^.*[/:\n]"

它返回

stackoverflow.com:1111/

它不应该返回符号“ /”,“:”或“ \ n”之一之前的第一个前缀吗?我该如何退货

stackoverflow.com:

使用正则表达式?

Questioner
Astralpirate
Viewed
1
The fourth bird 2020-12-02 17:21:24

你可以排除字符/ :\n使用否定的字符类^[^/:\n]*

使用\n带有-P一个Perl的正则表达式兼容:

echo "stackoverflow.com:1111/?a=b&c=d" | grep -oP "^[^/:\n]*"

或从字符串中排除空格而无需 -P

echo "stackoverflow.com:1111/?a=b&c=d" | grep -o "^[^/:[:space:]]*"

Bash演示


如果你也想匹配:末尾的内容,则可以匹配它^[^/:\n]*:

Bash演示