在 Bash 中使用egrep

在 Bash 中使用egrep

在下面的代码中,我收到一个错误,但我不知道为什么:

[name@unix ~]$cat test123
123
456
789
1011
1213
[name@unix ~]$egrep ^[0-9]{1,3}$ test123
egrep: ^[0-9]3$: No such file or directory
[name@unix ~]$egrep ^[0-9]{3}$ test123
123
456
789
[name@unix ~]$

当我执行 $man egrep 时,我会看到以下内容:

{n} 前一项正好匹配 n 次。 {n,} 前一项匹配 n 次或多次。 {n,m} 前面的项至少匹配 n 次,但不超过 m 次。

答案1

你的 shell 被解释{1,3}大括号扩展,导致grep看到

grep ^[0-9]1$ ^[0-9]3$ test123

因此,它需要^[0-9]3$一个附加的文件名参数。您应该始终引用正则表达式以防止 shell 进行此类扩展,即

egrep '^[0-9]{1,3}$' test123

相关内容