通过标记来替换文件中的多个字符串

我想替换文件中的多个字符串,例如 IP 地址,并想标记它们,以便任何重复出现的情况都将被标记为相同的名称。


例如,如果这是我的文件:


2018-09-13 19:00:00,317 INFO  -util.SSHUtil: Waiting for channel close

2018-09-13 19:00:01,317 INFO  -util.SSHUtil: Waiting for channel close

2018-09-13 19:00:01,891 INFO  -filters.BasicAuthFilter: Client IP:192.168.100.98

2018-09-13 19:00:01,891 INFO  -filters.BasicAuthFilter: Validating token ... 

2018-09-13 19:00:01,892 INFO  -authentication.Tokenization: Token:192.168.100.98:20180913_183401is present in map

2018-09-13 19:00:01,892 INFO  -configure.ConfigStatusCollector: status.

2018-09-13 19:00:01,909 INFO  -filters.BasicAuthFilter: Client IP:192.168.100.98

2018-09-13 19:00:01,909 INFO  -filters.BasicAuthFilter: Validating token ... 

2018-09-13 19:00:01,910 INFO  -authentication.Tokenization: Token:192.168.100.98:20180913_183401is present in map

2018-09-13 19:00:01,910 INFO  -restadapter.ConfigStatusService: configuration status.

2018-09-13 19:00:01,910 INFO  -configure.Collector: Getting configuration status.

2018-09-13 19:00:02,318 INFO  -util.SSHUtil: Processing the ssh command execution results standard output.

2018-09-13 19:00:02,318 INFO  -util.SSHUtil: Processing the ssh command execution standard error.

2018-09-13 19:00:02,318 INFO  -util.SSHUtil: Remote command using SSH execution status: Host     : [10.2.251.129]   User     : [root]   Password : [***********]    Command  : [shell ntpdate -u 132.132.0.88]  STATUS   : [0]

2018-09-13 19:00:02,318 INFO  -util.SSHUtil:    STDOUT   : [Shell access is granted to root

            14 Sep 01:00:01 ntpdate[16063]: adjust time server 132.132.0.88 offset 0.353427 sec

]

2018-09-13 19:00:02,318 INFO  -util.SSHUtil:    STDERR   : []

2018-09-13 19:00:02,318 INFO  -util.SSHUtil: Successfully executed remote command using SSH.

2018-09-13 19:00:02,318 INFO  Successfully executed the command on VCenter :10.2.251.129


红糖糍粑
浏览 131回答 1
1回答

红颜莎娜

您可以保留一组唯一 IP 地址,并使用它们在数组中的索引作为替换值。在下面的代码中,\1inreplace_func指的是正则表达式中的第一个匹配项。我们在数组中查找(必要时添加),正确格式化它,然后返回它以用作re.sub下面的替换值。像这样的东西:import fileinputimport reips = []def replace_func(match):    ip = match.expand(r'\1')    if ip not in ips:        ips.append(ip)    return 'IP_%s' % ips.index(ip)with fileinput.input('server.log', inplace=True, backup='.bak') as file:    for line in file:        print(re.sub(r'(\d+\.\d+\.\d+\.\d+)', replace_func, line), end='')
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python