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


当前回答

grep -irnw "filepath" -ve "pattern"

or

grep -ve "pattern" < file

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

其他回答

您可以单独使用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

下面的命令可以帮助你过滤包含子字符串“foo”的行。

cat file | grep -v "foo"

你实际上需要:

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

为了完整,ripgrep版本如下:

rg --files-without-match "pattern"

你可以结合文件类型和搜索路径,例如:

rg --files-without-match -t ruby "frozen_string_literal: true" app/

打开错误报告

正如@tukan所评论的,Ag有一个关于-L/——files-without-matches标志的开放错误报告:

Ggreer /the_silver_searcher: #238 -——files-without-matches不能正常工作

由于bug报告几乎没有进展,所以不应该依赖下面提到的-L选项,只要bug还没有解决。请使用本文中介绍的不同方法。引用bug报告的注释[强调我的]:

有最新进展吗?-L完全忽略文件第一行的匹配项。似乎如果这个问题不会很快得到解决,这个标志应该被完全移除,因为它根本不像宣传的那样有效。


Silver Searcher - Ag(预期功能-见错误报告)

作为grep的强大替代品,您可以使用the Silver Searcher - Ag:

一个类似于ack的代码搜索工具,专注于速度。

查看man ag,我们找到了-L或——files-without-matches选项:

... 选项 ... - l - files-without-matches 只打印不包含匹配项的文件名。

也就是说,从当前目录中递归搜索不匹配foo的文件:

ag -L foo

要只搜索当前目录中不匹配foo的文件,只需为递归指定——depth=0:

ag -L foo --depth 0