grep -e和grep -E选项有什么区别?


34

我想明白之间的差别grep -egrep -E。现在从grep manpage我那里得到:

-E,-extended-regexp

将PATTERN解释为扩展的正则表达式(请参见下文)。

-e PATTERN,--regexp =模式

使用PATTERN作为模式;保护以-开头的模式很有用

上面的解释对我来说没有意义。

因此,有人可以使用examples两者之间的区别以及何时使用哪个选项来向我解释一下。

PS:版本:grep(GNU grep)2.10



3
的目的-e实际上只是为了消除正则表达式以破折号开头的歧义。因此grep ---foounrecognized option: ---foo您可以grep -e ---foo对grep 说正则表达式---foo
2012年

Answers:


29

-e严格来说是用于指示您要匹配的模式的标志。-E控制是否需要转义某些特殊字符。

man grep进一步说明-E

   Basic vs Extended Regular Expressions
   In basic regular expressions the meta-characters ?, +, {, |, (, and ) lose their special meaning; instead use the backslashed versions \?, \+, \{, \|, \(, and \).

   Traditional  egrep  did  not  support  the  {  meta-character, and some egrep implementations support \{ instead, so portable scripts should avoid { in grep -E patterns and should use [{] to match a
   literal {.

   GNU grep -E attempts to support traditional usage by assuming that { is not special if it would be the start of an invalid interval specification.  For example, the command grep -E '{1' searches for
   the two-character string {1 instead of reporting a syntax error in the regular expression.  POSIX.2 allows this behavior as an extension, but portable scripts should avoid it.

2
因此,这就是为什么我echo "hello" | grep -o -e 'h|l'因为|失去其特殊含义而没有输出而我却echo "hello" | grep -o -E 'h|l'得到期望的输出时的原因。

2
是。echo "hello" | grep -o -e 'h' -e 'l'如果您想-E在这种情况下扔掉,将可以工作。
hafichuk 2012年

3
grep -e -o 'h|l'将按字面上匹配,h|lgrep -e -o 'h\|l'将匹配hl与-E
恰好

@ronnie不幸的是,您需要200多个信誉才能让SE网站之间的“功能”跟随您……
hafichuk 2012年

5

grep -e允许使用多个字符串进行搜索:'grep -e 'abc' -e 'def' -e '123'将查找所有三个字符串:abc以及def123

这与代表grep 'abc\|def\|123'位置的工作原理非常相似\|or但阅读起来可能更清晰。

正如grep -E上面已经解释了最重要的事实一样,我只想在一个非常类似的问题上添加关于该主题的总结:在Bash中查找双字符的正则表达式


3

见下文

/扩展

grep理解正则表达式语法的三种不同版本:“基本”,“扩展”和“ perl”。在GNU grep中,基本语法和扩展语法之间的可用功能没有区别。在其他实现中,基本正则表达式的功能较弱。以下描述适用于扩展的正则表达式;基本正则表达式的差异将在后面总结。Perl正则表达式提供了其他功能,并在pcresyntax(3)和pcrepattern(3)中进行了介绍,但可能并非在每个系统上都可用。

所以,再次。

在GNU grep中,基本语法和扩展语法之间的可用功能没有区别


2
所述功能性是基本和扩展之间的相同但语法稍有不同。正则表达式特殊字符像()|等需要被反斜杠转义有基本的正则表达式的特殊含义,而不是在扩展(他们需要进行转义被视为一个字符串字面)
中科院

1

只是为了详细说明该-e选项。-e通常是可选的:

grep PATTERN

等同于

grep -e PATTERN

除非如先前的“答案”和手册页中所述,否则存在多个搜索模式,或者为了保护以连字符(-)开头的模式。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.