指定目录和globs方式的区别

  • 本文关键字:方式 区别 globs grep
  • 更新时间 :
  • 英文 :


假设我在一个项目文件夹中,想要使用grep -rnigrep一个关键字。这三个命令有什么区别?

grep -rni . -e "keyword"

grep -rni * -e "keyword"

grep -rni **/* -e "keyword"

我对此进行了测试,并注意到前两个命令返回相同数量的匹配项,尽管顺序不同。然而,第三个返回的匹配项明显多于前两个。

有任何理由使用第三个吗?它返回更多匹配重复项的原因是什么?

首先,差异与-n-i参数无关。

来自grep手册页:

-n, --line-number
Prefix each line of output with the 1-based line number within its input file.
-i, --ignore-case
Ignore case distinctions in patterns and input data, so that characters that differ only in case match each other.
-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.
所以,区别实际上在于字符串***/*

是如何被shell解释的.对于.,您将当前目录作为参数传递给grep。这里并不神秘,因为grep就是遍历当前工作目录的grep。

使用*,将当前目录中的每个文件作为参数传递给grep(包括目录)。

现在,假设您有以下目录结构:
├── file.txt
├── one
│   └── file.txt
└── two
└── file.txt

运行grep -rni * -e keyword被翻译为:

grep -rni file.txt one two -e keyword

这个条件grep按顺序迭代文件和嵌套目录。

最后,grep -rni **/* -e keyword将转换成以下命令行:

grep -rni file.txt one one/file.txt two two/file.txt -e keyword

最后一种方法的问题是一些文件将被处理多次。例如:one/file.txt将被处理两次:一次是因为它显式地在参数列表中,另一次是因为它属于目录one,该目录也在参数列表中。

最新更新