由于windows上面没有类似linux上面的grep命令,所以下面的python脚本来代替其能力。
grep.py
import argparse
import re
if __name__ == '__main__':
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument("grep")
arg_parser.add_argument("file")
arg_parser.add_argument("-o", "--out", help="存储路径", required=False)
args = arg_parser.parse_args()
logfile = open(args.file, "r")
grep = args.grep
try:
of = open(args.out, mode="w") if args.out else None
with open(args.file, mode="r", encoding='utf-8') as f:
line = f.readline()
while line:
if re.search(grep, line):
if of:
of.write(line)
else:
print(line, end="")
line = f.readline()
if of:
of.close()
except KeyboardInterrupt:
pass
对文件内容进行过滤:python3 grep.py 匹配字符 file.log
对文件内容进行过滤并保存到文件:python3 grep.py 匹配字符 file.log -o temp.log