首页 > 代码库 > python实现grep

python实现grep

import sysimport osimport redef usage():    print "[Usage]: python grep.py filename grepString."if len(sys.argv) != 3:    usage()    sys.exit(1)if os.path.isfile(sys.argv[1]):    passelse:    usage()    sys.exit(2)f = open(sys.argv[1])content = f.read()f.close()s = "\n".join(re.findall(sys.argv[2]+.*, content))print s

【实现思路】

1. 读入文件;

2. 利用python的正则表达式模块,查找匹配字符串;

python实现grep