python grep reverse matching

我与影子孤独终老i 提交于 2019-12-24 19:47:07

问题


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


回答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.




回答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'),
    )

def check_file(fn):
    f = open(fn, 'r')
    content = f.read()
    f.close()
    for rx, rx_desc in WARNING_RX:
        if not rx.search(content):
            print('%s: not found: %s' % (fn, rx_desc))


来源:https://stackoverflow.com/questions/2910106/python-grep-reverse-matching

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!