如果括号中只有一个条目,则 grep --include=*.{cpp,cc,cxx} 不起作用

grep --include=*.{cpp,cc,cxx} doesn't work if there's only one entry in brackets

我用 grep -F -e "function1" --include=*.{cpp,c} . -r -n 找到了 function1 的用途,但后来意识到我可以加快它的速度,所以我从 --include 中删除了 c 但后来它不起作用.

为什么?

这不起作用 ->grep -F -e "function1" --include=*.{cpp} . -r -n

它会 运行 但不会 return 任何东西。如果我添加第二个项目,即 --include=*.{cpp,dsafjlsadfsaldf} 那么它就可以了。

观察:

$ echo {a,b}
a b
$ echo {a}
{a}

换句话说,大括号扩展 只有在大括号内还有两个元素时才有效。如果只有一个元素,请不要使用大括号。

同样,但要解决您正在使用的特定选项:

$ echo  --include=*.{cpp,c} 
--include=*.cpp --include=*.c
$ echo  --include=*.{cpp} 
--include=*.{cpp}

要使后者正常工作,请移除大括号:

$ echo  --include=*.cpp
--include=*.cpp

您依赖于 shell 的 "brace expansion" 功能。引用 Bash 手册,

A correctly-formed brace expansion must contain unquoted opening and closing braces, and at least one unquoted comma or a valid sequence expression.

没有任何逗号,文本不符合大括号扩展的条件。