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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 05:37:32  来源:igfitidea点击:

grep with regexp: whitespace doesn't match unless I add an assertion

regexlinuxbashgrep

提问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 grepmanpage. 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, grepis sometimes stuck in the past because you want to make sure your grepcommand remains compatible with older versions of grep.

不幸的是,grep有时会停留在过去,因为您想确保您的grep命令与旧版本的grep.

Some systems have egrepwith some extensions. Others allow you to use grep -Eto get them. Still others have a grep -Pthat allows you to use Perl extensions. I believe Linux systems' grep command can use the -Pextension 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 -Pswitch, but not older versions.

有些系统有egrep一些扩展。其他人允许您使用grep -E来获取它们。还有一些grep -P允许您使用 Perl 扩展。我相信 Linux 系统的 grep 命令可以使用-P大多数 Unix 系统中没有的扩展名,除非有人用 GNU 版本替换了 grep。较新版本的 Mac OS X 也支持该-P开关,但不支持旧版本。

回答by dogbane

grepdoesn't support the complete set of regular expressions, so try using -Pto 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'