如何找到所有不包含文本字符串的文件?

cwd*_*cwd 45 grep find recursive

我可以使用什么简洁的命令来查找所有不包含文本字符串的文件?

我试过这个(使用 -v 来反转 grep 的参数)但没有运气:

find . -exec grep -v -l shared.php {} \;
Run Code Online (Sandbox Code Playgroud)

有人说这行得通:

find . ! -exec grep -l shared.php {} \;
Run Code Online (Sandbox Code Playgroud)

但它似乎对我不起作用。

这个页面有这个例子:

find ./logs -size +1c  > t._tmp
while read filename
do
     grep -q "Process Complete" $filename
     if [ $? -ne 0 ] ; then
             echo $filename
     fi
done < t._tmp
rm -f t_tmp
Run Code Online (Sandbox Code Playgroud)

但这很麻烦,而且一点也不简洁。

ps:我知道这grep -L *会做到这一点,但是我真正想知道的是如何将 find 命令与 grep 结合使用来排除文件。

pss:我也不确定如何让 grep 包含带有grep -L *语法的子目录,但我仍然想知道如何使用它find:)

Kev*_*vin 74

如果您将-v -l(有任何行不匹配的-L文件)更改为(没有行匹配的文件),您的查找应该可以工作,但您也可以使用grep's recursive ( -r) 选项:

grep -rL shared.php .
Run Code Online (Sandbox Code Playgroud)


Sac*_*kar 10

find . -type f | xargs grep -H -c 'shared.php' | grep 0$ | cut -d':' -f1    
Run Code Online (Sandbox Code Playgroud)

或者

find . -type f -exec grep -H -c 'shared.php' {} \; | grep 0$ | cut -d':' -f1
Run Code Online (Sandbox Code Playgroud)

在这里,我们计算-c文件中匹配行的数量(使用),如果计数为 0,则它是所需的文件,因此我们从输出中删除第一列,即文件名。

  • 这非常复杂。请参阅 [凯文的回答](http://unix.stackexchange.com/a/26837)。 (7认同)
  • 这不仅“非常复杂”而且_错误_,因为它还会列出包含与模式匹配的 10 行的倍数的所有文件。即使修复了 `grep`,这仍然会假设没有包含 `:` 或 _newline_ 字符的文件名...... (7认同)

don*_*sti 5

我知道这grep -L *会做到这一点,但是我真正想知道的是如何将find命令与grep排除文件结合使用

您可以使用findgrep喜欢这样的:

find . -type f ! -exec grep -q 'PATTERN' {} \; -print
Run Code Online (Sandbox Code Playgroud)

-print仅当前面的表达式:! -exec ... {}计算为时才执行此处true
因此,对于每个文件中发现,grep -q 'PATTERN'exec贡献,如果结果是false,那么整个表达式! -exec grep -q 'PATTERN'评估为true和该文件名被print

  • 那个有标准和便携的好处。 (2认同)