使用Perl正则表达式提取单行文本指定数值并求和
给定以下日志文本:
Total number of commands sent: <number_commands> : number_commands=6 Total number of Special commands sent: <number_commands> : number_commands=0 Total number of unknown commands: <number_commands> : number_commands=0 Total number of command parsing errors: <number_errors> : number_errors=1 Total number of fatal parsing errors: <number_errors> : number_errors=2
Total number of calls made to PROCESS1: <number_calls> : number_calls=0 Total number of calls made with time-out: <number_calls> : number_calls=7 Total number of calls ack by the PROCESS1: <number_calls> : number_calls=0 Total number of calls nack post-poned by the PROCESS1: <number_calls> : number_calls=5 Total number of calls nack rejected by the PROCESS1: <number_calls> : number_calls=5
需通过Perl正则表达式提取并计算三类数值总和:
- tot_nack:所有包含"nack"的
number_calls数值之和(示例结果:10) - tot_timeout:包含"time-out"的
number_calls数值(示例结果:7) - tot_errors:所有
number_errors数值之和(示例结果:3)
#!/usr/bin/perl use strict; use warnings; # 读取日志文本 my $log_content = do { local $/; <DATA> }; # 初始化结果变量 my ($tot_nack, $tot_timeout, $tot_errors) = (0, 0, 0); # 计算tot_nack:匹配所有含nack的number_calls并累加 while ($log_content =~ /calls nack .*? number_calls=(\d+)/g) { $tot_nack += $1; } # 提取tot_timeout:匹配time-out对应的number_calls if ($log_content =~ /calls made with time-out.*? number_calls=(\d+)/) { $tot_timeout = $1; } # 计算tot_errors:匹配所有number_errors并累加 while ($log_content =~ /number_errors=(\d+)/g) { $tot_errors += $1; } # 输出结果 print "tot_nack: $tot_nack\n"; print "tot_timeout: $tot_timeout\n"; print "tot_errors: $tot_errors\n"; __DATA__ Total number of commands sent: <number_commands> : number_commands=6 Total number of Special commands sent: <number_commands> : number_commands=0 Total number of unknown commands: <number_commands> : number_commands=0 Total number of command parsing errors: <number_errors> : number_errors=1 Total number of fatal parsing errors: <number_errors> : number_errors=2 Total number of calls made to PROCESS1: <number_calls> : number_calls=0 Total number of calls made with time-out: <number_calls> : number_calls=7 Total number of calls ack by the PROCESS1: <number_calls> : number_calls=0 Total number of calls nack post-poned by the PROCESS1: <number_calls> : number_calls=5 Total number of calls nack rejected by the PROCESS1: <number_calls> : number_calls=5
- 提取tot_nack:使用全局匹配
/calls nack .*? number_calls=(\d+)/g,捕获每个含nack条目后的数字并累加,最终得到5+5=10 - 提取tot_timeout:使用单次匹配
/calls made with time-out.*? number_calls=(\d+)/,直接捕获time-out对应的数字7 - 计算tot_errors:使用全局匹配
/number_errors=(\d+)/g,捕获所有number_errors的数字并累加,得到1+2=3
tot_nack: 10 tot_timeout: 7 tot_errors: 3
内容的提问来源于stack exchange,提问作者user3303852

