Linux grep with regexp:除非我添加断言,否则空格不匹配
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7013152/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
grep with regexp: whitespace doesn't match unless I add an assertion
提问by Ankur Agarwal
GNU grep 2.5.4 on bash 4.1.5(1) on Ubuntu 10.04
GNU grep 2.5.4 bash 4.1.5(1) Ubuntu 10.04
This matches
这匹配
$ echo "this is a line" | grep 'a[[:space:]]\+line'
this is a line
But this doesn't
但这不
$ echo "this is a line" | grep 'a\s\+line'
But this matches too
但这也很匹配
$ echo "this is a line" | grep 'a\s\+\bline'
this is a line
I don't understand why #2 does not match (whereas # 1 does) and #3 also shows a match. Whats the difference here?
我不明白为什么#2 不匹配(而#1 匹配)并且#3 也显示匹配。这里有什么区别?
采纳答案by David W.
Take a look at your grep
manpage. Perl added a lot of regular expression extensions that weren't in the original specification. However, because they proved so useful, many programs adopted them.
看看你的grep
联机帮助页。Perl 添加了许多原始规范中没有的正则表达式扩展。然而,由于它们被证明非常有用,许多程序都采用了它们。
Unfortunately, grep
is sometimes stuck in the past because you want to make sure your grep
command remains compatible with older versions of grep
.
不幸的是,grep
有时会停留在过去,因为您想确保您的grep
命令与旧版本的grep
.
Some systems have egrep
with some extensions. Others allow you to use grep -E
to get them. Still others have a grep -P
that allows you to use Perl extensions. I believe Linux systems' grep command can use the -P
extension which is not available in most Unix systems unless someone has replaced the grep with the GNU version. Newer versions of Mac OS X also support the -P
switch, but not older versions.
有些系统有egrep
一些扩展。其他人允许您使用grep -E
来获取它们。还有一些grep -P
允许您使用 Perl 扩展。我相信 Linux 系统的 grep 命令可以使用-P
大多数 Unix 系统中没有的扩展名,除非有人用 GNU 版本替换了 grep。较新版本的 Mac OS X 也支持该-P
开关,但不支持旧版本。
回答by dogbane
grep
doesn't support the complete set of regular expressions, so try using -P
to enable perl regular expressions. You don't need to escape the +
i.e.
grep
不支持完整的正则表达式集,所以尝试使用-P
启用 perl 正则表达式。你不需要逃避+
ie
echo "this is a line" | grep -P 'a\s+line'