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


当前回答

我的grep没有任何-L选项。我确实找到了解决办法。

这些想法是:

将包含相应字符串的所有文件名转储到txt1.txt。 将目录中的所有文件名转储到txt2.txt文件中。 使用diff命令区分2个转储文件。 Grep 'foo' *.log | cut -c1-14 | uniq > txt1.txt Grep * *.log | cut -c1-14 | uniq > txt2.txt Diff txt1.txt txt2.txt | grep ">"

其他回答

find *20161109* -mtime -2|grep -vwE "(触发器)"

你可以在"find"下指定过滤器,在"grep -vwE"下指定排除字符串。如果你也需要对修改后的时间进行过滤,请在find下使用mtime。

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

cat file | grep -v "foo"

问题

我需要重构一个使用.phtml文件编写HTML使用内联PHP代码的大型项目。我想用胡子模板代替。我想找到任何。phtml贾尔斯不包含字符串新的胡子,因为这些仍然需要重写。

解决方案

找到。- iname”*。phtml' -exec grep -H -E -o -c '新胡子' {}\;| grep:0$ | sed 's/..$//'

解释

在管道之前:

Find

找到。递归地查找文件,从这个目录开始

- iname”*。文件名必须包含.phtml (i使其不区分大小写)

-exec 'grep -H -E -o -c 'new Mustache'{}'在每个匹配的路径上执行grep命令

Grep

始终用输出行打印文件名标题。

将pattern解释为扩展的正则表达式(即force grep 表现得像egrep)。

-o只打印匹配的行。

-c只将选定的行数写入标准输出。


这将给我一个以.phtml结尾的所有文件路径的列表,并计算字符串new Mustache在每个路径中出现的次数。

$> find . -iname '*.phtml$' -exec 'grep -H -E -o -c 'new Mustache' {}'\;

./app/MyApp/Customer/View/Account/quickcodemanagestore.phtml:0
./app/MyApp/Customer/View/Account/studio.phtml:0
./app/MyApp/Customer/View/Account/orders.phtml:1
./app/MyApp/Customer/View/Account/banking.phtml:1
./app/MyApp/Customer/View/Account/applycomplete.phtml:1
./app/MyApp/Customer/View/Account/catalogue.phtml:1
./app/MyApp/Customer/View/Account/classadd.phtml:0
./app/MyApp/Customer/View/Account/orders-trade.phtml:0

第一个管道grep:0$将该列表过滤为只包含以:0结尾的行:

$> find . -iname '*.phtml' -exec grep -H -E -o -c 'new Mustache' {} \; | grep :0$

./app/MyApp/Customer/View/Account/quickcodemanagestore.phtml:0
./app/MyApp/Customer/View/Account/studio.phtml:0
./app/MyApp/Customer/View/Account/classadd.phtml:0
./app/MyApp/Customer/View/Account/orders-trade.phtml:0

第二条管道sed 's/..$//'去掉每行的最后两个字符,只留下文件路径。

$> find . -iname '*.phtml' -exec grep -H -E -o -c 'new Mustache' {} \; | grep :0$ | sed 's/..$//'

./app/MyApp/Customer/View/Account/quickcodemanagestore.phtml
./app/MyApp/Customer/View/Account/studio.phtml
./app/MyApp/Customer/View/Account/classadd.phtml
./app/MyApp/Customer/View/Account/orders-trade.phtml

打开错误报告

正如@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
grep -irnw "filepath" -ve "pattern"

or

grep -ve "pattern" < file

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