python grep 反向匹配
我想构建一个小的 python 脚本,它基本上与 grep 执行相反的操作。 我想匹配没有“searched_string”的目录/子目录中的文件。
到目前为止,我已经做到了:
import os
filefilter = ['java','.jsp']
path= "/home/patate/code/project"
for path, subdirs, files in os.walk(path):
for name in files:
if name[-4:] in filefilter :
print os.path.join(path, name)
这个小脚本将列出每个子目录中带有“java”或“jsp”扩展名的每个文件,并将输出它们的完整路径。
我现在想知道如何完成其余的工作,例如,如果我忘记了一个文件中的会话管理条目(允许任何人直接访问文件),我希望能够搜索: “if (!user.hasPermission”并列出不包含此字符串的文件。
任何帮助将不胜感激!
谢谢
I would like to build a small python script that basicaly does the reverse of grep.
I want to match the files in a directory/subdirectory that doesn't have a "searched_string".
So far i've done that:
import os
filefilter = ['java','.jsp']
path= "/home/patate/code/project"
for path, subdirs, files in os.walk(path):
for name in files:
if name[-4:] in filefilter :
print os.path.join(path, name)
This small script will be listing everyfiles with "java" or "jsp" extension inside each subdirectory, and will output them full path.
I'm now wondering how to do the rest, for example i would like to be able if I forgot a session management entry in one file (allowing anyone a direct file access), to search for :
"if (!user.hasPermission" and list the file which does not contain this string.
Any help would be greatly appreciated !
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
要检查路径绑定到变量
f
的文件是否包含绑定到名称s
的字符串,最简单的(并且对于大多数合理大小的文件来说是可接受的)类似于在您的os.walk 循环中,您分别拥有根路径和文件名,因此
(无条件打印的内容)是您要打开和检查的路径。
To check if a file with a path bound to variable
f
contains a string bound to names
, simplest (and acceptable for most reasonably-sized files) is something likeIn your
os.walk
loop, you have the root path and filename separately, so(what you're unconditionally printing) is the path you want to open and check.
不是打印文件名,而是调用函数来检查文件内容是否与您想要在源文件中包含的文本不匹配。在这种情况下,我使用
check_file()
,如下所示:Instead of printing file name call function that will check if file content do not match texts you want to have in source files. In such cases I use
check_file()
that looks like this: