如何找出当前目录中不包含单词foo(使用grep)的文件?
当前回答
问题
我需要重构一个使用.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
其他回答
下面的命令不需要find通过使用第二个grep来过滤svn文件夹。
grep -rL "foo" ./* | grep -v "\.svn"
为了完整,ripgrep版本如下:
rg --files-without-match "pattern"
你可以结合文件类型和搜索路径,例如:
rg --files-without-match -t ruby "frozen_string_literal: true" app/
下面的命令给出了所有不包含foo模式的文件:
find . -not -ipath '.*svn*' -exec grep -H -E -o -c "foo" {} \; | grep 0
你实际上需要:
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