Python: python实现grep查找功能
June 3, 2015
写这个程序的原因是Windows下的搜索功能不好用,有尝试过下载一下小工具来补偿搜索功能,但都不尽如人意,所以就干脆自己写一个了.
功能:在任何装有python2.7(或2.7以上3.0以下版本)的机器上运行文件名搜索、文件内容搜索.
代码 grep.py:
import os import re import argparse def inred( s ): return"%s[31;2m%s%s[0m>"%(chr(27), s, chr(27)) def parseInput(): parser = argparse.ArgumentParser() parser.add_argument("-p>", nargs='*') parser.add_argument('-s',nargs='*') parser.add_argument('-k',nargs='*') args = parser.parse_args() return args.p, args.s, args.k def searchFile(mfile,patterns): fr = open(mfile,'r') line_num = 0 flag = True while True: line = fr.readline() line_num += 1 if line: for eachp in patterns: if(eachp.findall(line)): if flag: print mfile flag = False print "line>",line_num,line, else: break if not flag: print ">" if __name__ == "__main__>": mpaths,filefilters,mkeys = parseInput() if mpaths == None: mpaths = [os.getcwd()] print "Search paths:>",mpaths print "File filters:>",filefilters print "Search keys:>",mkeys print ">" file_pattern = [] key_pattern = [] if filefilters: for eachff in filefilters: file_pattern.append(re.compile(eachff,re.I)) if mkeys: for eachkey in mkeys: key_pattern.append(re.compile(eachkey,re.I)) for eachp in mpaths: list_dirs = os.walk(eachp) for root, dirs, files in list_dirs: for f in files: if filefilters != None: for eachfp in file_pattern: if(eachfp.findall(f)): fname = os.path.join(root, f) if mkeys != None: searchFile(fname,key_pattern) else: print fname break elif mkeys != None: fname = os.path.join(root, f) searchFile(fname,key_pattern) else: print 'USAGE: -p paths -s file_filters(must be regular expression) -k keys(must be regular expression)' quit()
grep.py -p <you_dir> -s <file_filter_re_pattern> -k <key_word_re_pattern>
这样就可以查找指定目录下的文件内容,如果你的命令行已经在该目录,则-p选项可选,如果不指定文件名过滤,-s选项可选.如果想直接搜索文件名则可省去-k选项
grep.py -p-s
另外,-s和-k选项支持正则表达式,所以要注意使用转义符号,各个选项都支持多参数.
0 Comments