1.替换

#!/bin/python
#encoding:utf8

import time,re,os,sys

filename = sys.argv[1]
newfilename = filename+'new'

file = open(filename)

with open(newfilename,'w') as f:

    while True:
        where = file.tell()
        line = file.readline()
        if not line:
            break
        else:
            if "cardNo" in line:
                cardNo = re.search(r'cardNo\:(\d+)',line,re.M|re.I).group()
                s =  cardNo.split(":")[1]
                results = 'cardNo:'+s[:6]+6*'*'+s[-4:]
                line = re.sub(r'cardNo\:(\d+)',results,line)
            f.write(line)

 

2.实时更新替换
 

#!/bin/python
#encoding:utf8

import time,re,os

#file = open('/data/apps/logs/roller.log.%s' % (time.strftime("%Y-%m-%d", time.localtime())))

file = open('./csume.log')

with open('./1.log','w') as f:

    while True:
        where = file.tell()
        line = file.readline()
        if not line:
            time.sleep(1)
            file.seek(where)
        else:
            if "cardNo" in line:
                cardNo = re.search(r'\"cardNo\":\"(\d+)\"',line,re.M|re.I).group()
                print cardNo
                s =  cardNo.split(":")[1]
                results = '"cardNo":'+s[:7]+6*'*'+s[-5:]
                line = re.sub(r'\"cardNo\":\"(\d+)\"',results,line)
            f.write(line)

 

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐