来自man grep
:
Repetition
A regular expression may be followed by one of several repetition
operators:
? The preceding item is optional and matched at most once.
* The preceding item will be matched zero or more times.
+ The preceding item will be matched one or more times.
{n} The preceding item is matched exactly n times.
{n,} The preceding item is matched n or more times.
{n,m} The preceding item is matched at least n times, but not more
than m times.
由于前三个 (or 2) ,该示例grep 'a\{2,3\}' new
也与行匹配。该行的其余部分并不重要。aaaa
a
如果您希望真的只有 2 或 3 个连续a
匹配,您可以使用该-o
标志。但请注意,这将输出aa
并aaa
从带有aaaaa
. 为避免这种情况,您必须使用附加信息,例如示例换行符^
和$
.
顺便提一句。我建议使用该-E
标志(或egrep
相同的标志),以便您扩展正则表达式支持。然后,您不必转义括号。
用于输入
aaaaa
aaaa
aaa
aa
a
调用grep -o -E '^a{2,3}$'
将给出输出:
aaa
aa