Python Grep Reverse Matching
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
Solution 1:
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
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.
Solution 2:
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:
WARNING_RX = (
(re.compile(r'if\s+\(!\s+user.hasPermission'), 'user.hasPermission'),
(re.compile(r'other regexp you want to have'), 'very important'),
)
defcheck_file(fn):
f = open(fn, 'r')
content = f.read()
f.close()
for rx, rx_desc in WARNING_RX:
ifnot rx.search(content):
print('%s: not found: %s' % (fn, rx_desc))
Post a Comment for "Python Grep Reverse Matching"