星号 (*) 在 grep -nri "searchString" * 中有什么作用?

Vis*_*kar 4 command-line grep

通常在使用 grep 搜索时,我使用的命令是这样的:

grep -nri "String"
Run Code Online (Sandbox Code Playgroud)

而我的大多数同事都是这样做的:

grep -nri "String" *
Run Code Online (Sandbox Code Playgroud)

后者做什么(*部分)?

mur*_*uru 8

grepwith-r标志递归地对指定目录中的所有文件进行操作:

-r, --recursive
      Read all files  under  each  directory,  recursively,  following
      symbolic  links only if they are on the command line.  Note that
      if  no  file  operand  is  given,  grep  searches  the   working
      directory.  This is equivalent to the -d recurse option.
Run Code Online (Sandbox Code Playgroud)

默认情况下,如果没有给出目录,grep则将处理当前目录中的所有文件。

在 中grep -r ... *,shell 扩展*到当前目录中的所有文件和目录(通常除了以 a 开头的那些.),grep然后递归地处理它们

因此,如果您有一个包含以下内容的目录,例如:

.git/
.gitignore
foo/
foo/.foo2
foo/link2 -> /foo2/bar2
bar
link1 -> /foo/bar
Run Code Online (Sandbox Code Playgroud)

其中以 结尾的名称/是目录,然后grep -r还将处理.gitignore文件和 中的所有内容.git,但grep -r ... *会扩展到grep -r ... foo bar,并最终排除.gitignore.git(但会包括foo/.foo2)。

还要注意有关符号链接的一点 - 如果 的扩展中的文件之一*是符号链接,则符号链接目标将在您使用*. 所以 with *,/foo/bar将作为 的目标处理link1,但不会/foo2/bar2作为 的目标处理link2

整体效果:

                                 w/o *           with *
.git/                              +                -
.gitignore                         +                -
foo/                               +                +
foo/.foo2                          +                +
foo/link2 -> /foo2/bar2            -                -
bar                                +                +
link1 -> /foo/bar                  -                +
Run Code Online (Sandbox Code Playgroud)

当然,您想做什么取决于您是否希望将这些文件和目录包含在搜索中;但我倾向于让grep自己做排除和包括使用--exclude/--include和其他选项。

  • 忍者。也正是我想说的…… (2认同)