如何找出当前目录中不包含单词foo(使用grep)的文件?


当前回答

下面的命令给出了所有不包含foo模式的文件:

find .  -not  -ipath '.*svn*' -exec  grep  -H -E -o -c  "foo"  {} \; | grep 0

其他回答

当grep没有-L选项时(例如IBM AIX),只有grep和shell时的另一种选择:

for file in * ; do grep -q 'my_pattern' $file || echo $file ; done

您可以单独使用grep(没有find)来完成。

grep -riL "foo" .

这是对grep上使用的参数的解释

     -L, --files-without-match
             each file processed.
     -R, -r, --recursive
             Recursively search subdirectories listed.

     -i, --ignore-case
             Perform case insensitive matching.

如果你使用l(小写),你将得到相反的(文件匹配)

     -l, --files-with-matches
             Only the names of files containing selected lines are written

当您使用find时,您有两个基本选项:在find完成搜索后过滤结果,或者使用一些内置选项来阻止find考虑那些匹配某些给定模式的文件和dirs。

如果您在大量的文件和dirs上使用前一种方法。您将使用大量的CPU和RAM来将结果传递给第二个进程,而第二个进程反过来也会使用大量的资源来过滤结果。

如果你使用-not关键字作为一个find参数,你将阻止任何与后面的name或-regex参数上的字符串匹配的路径被考虑,这将更有效。

find . -not -regex ".*/foo/.*" -regex ".*"

然后,任何没有被-not过滤掉的路径都将被后续的-regex参数捕获。

grep -irnw "filepath" -ve "pattern"

or

grep -ve "pattern" < file

上面的命令会给我们结果,因为-v找到了正在搜索的模式的倒数

如果你正在使用git,它会搜索所有被跟踪的文件:

git grep -L "foo"

如果你打开了**子目录globbing,你可以在跟踪文件的子集中搜索(在.bashrc中使用shopt -s globstar):

git grep -L "foo" -- **/*.cpp