grep returns "<regular expression>" 没有那个文件或目录

grep returns "<regular expression>" No such file or directory

我有以下正则表达式来匹配 phone 数字。正则表达式有效(123)123-123,但我对最后的结果感到困惑。

user@host: grep -l -v -f *.txt -E "(\d{3})-\d{3}-\d{3}"
f2.txt
f3.txt
f4.txt
grep: (\d{3})-\d{3}-\d{3}: No such file or directory

为什么 grep 搜索正则表达式?

这里是 ls:

user@host:/tmp# ls
f1.txt  f2.txt  f3.txt  f4.txt  

grep 用法是

grep [OPTION]... PATTERN [FILE]...

您的命令扩展为

grep -l -v -f f1.txt f2.txt f3.txt f4.txt -E "(\d{3})-\d{3}-\d{3}"

相当于

grep -f f1.txt -l -v -E f2.txt f3.txt f4.txt "(\d{3})-\d{3}-\d{3}"

即"use the file f1.txt as a file containing patterns, and search the files f2.txt, f3.txt, f4.txt and (\d{3})-\d{3}-\d{3}. Apply options -l, -v and -E everywhere."

也许你的意思是

grep -l -v -E "(\d{3})-\d{3}-\d{3}" *.txt

代替?

relevant part of the man page内容如下:

-f <i>FILE</i>, --file=<i>FILE</i>
Obtain patterns from FILE, one per line. If this option is used multiple times or is combined with the -e (--regexp) option, search for all patterns given. The empty file contains zero patterns, and therefore matches nothing.

旁注:如果您使用 -E,则必须转义文字括号。另外,据我所知,不支持 \d,因此您必须使用

grep -P '\(\d{3}\)-\d{3}-\d{3}'

grep -E '\([[:digit:]]{3}\)-[[:digit:]]{3}-[[:digit:]]{3}'