python grep反向匹配 [英] python grep reverse matching
问题描述
我想构建一个小的python脚本,它基本上与grep相反.我想匹配没有searched_string"的目录/子目录中的文件.
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)
这个小脚本将列出每个子目录中带有java"或jsp"扩展名的每个文件,并输出它们的完整路径.
This small script will be listing everyfiles with "java" or "jsp" extension inside each subdirectory, and will output them full path.
我现在想知道如何做其余的工作,例如,如果我忘记了一个文件中的会话管理条目(允许任何人直接访问文件),我希望能够搜索:"if (!user.hasPermission" 并列出不包含此字符串的文件.
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.
任何帮助将不胜感激!
谢谢
推荐答案
检查路径绑定到变量 f
的文件是否包含绑定到 name s
的字符串, 最简单的(对于大多数合理大小的文件都可以接受)就像
To check if a file with a path bound to variable f
contains a string bound to name s
, simplest (and acceptable for most reasonably-sized files) is something like
with open(f) as fp:
if s in fp.read():
print '%s has the string' % f
else:
print '%s doesn't have the string' % f
在你的 os.walk
循环中,你分别有根路径和文件名,所以
In your os.walk
loop, you have the root path and filename separately, so
f = os.path.join(path, name)
(您无条件打印的)是您要打开和检查的路径.
(what you're unconditionally printing) is the path you want to open and check.
这篇关于python grep反向匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!