一个Python3脚本,可以实现从某一目录下的所有文本文件例如日志中,根据关键字提取指定行,用法为python3 脚本名称 检索路径 关键字(多个关键字用逗号分隔) 关键字向上取行数 关键字向下取行数,例如:python3 findmsg.py /tmp/logs/ warn,error 5 10

import os,linecache,sys

def setcolor(text,keyword):
    perfix = '\033[1;35m'
    suffix = '\033[0m'
    keywordlist = keyword.split(',')
    for i in keywordlist:
        text = text.replace(i,perfix+i+suffix)
    return text

def findmsg_h(filedir,msg,unum,dnum):
    worklist = os.listdir(filedir)
    msglist = msg.split(',')
    for i in range(0,len(worklist)):
        path = os.path.join(filedir,worklist[i])
        if os.path.isfile(path):
            print('当前查找的文件为' +path)
            msgfile = open(path)
            for nums,value in enumerate(msgfile):
                if all(msgtotal in value for msgtotal in msglist):
                    print('当前匹配的关键字为'+str(msglist))
                    for point in range(nums-int(unum)+1,nums+int(dnum)+1+1,):
                        linetext = linecache.getline(path,point).strip()
                        print(point,setcolor(linetext,msg))
                    print('=================================================')
            msgfile.close()
    print('匹配完成')
    return

findmsg_h(sys.argv[1],sys.argv[2],sys.argv[3],sys.argv[4])
分类: Python3

0 条评论

发表回复

Avatar placeholder

您的邮箱地址不会被公开。 必填项已用 * 标注