Regex perl grep 10行日志
我很有兴趣在匹配正则表达式“critical”或“error”之前抓取10行。 目前,我正在打印$,它只提供正则表达式匹配的行 我用perl编写了以下代码:Regex perl grep 10行日志,regex,perl,Regex,Perl,我很有兴趣在匹配正则表达式“critical”或“error”之前抓取10行。 目前,我正在打印$,它只提供正则表达式匹配的行 我用perl编写了以下代码: #!/usr/bin/perl -w use strict; open LOG, "/Users/erangross/Projects/perl/log" or die; while (<LOG>){ if (/critical | error/){ open (myFile, '>>par
#!/usr/bin/perl -w
use strict;
open LOG, "/Users/erangross/Projects/perl/log" or die;
while (<LOG>){
if (/critical | error/){
open (myFile, '>>parser_log.txt');
print myFile $_;
}
}
#/usr/bin/perl-w
严格使用;
打开日志“/Users/erragross/Projects/perl/LOG”或die;
而(){
如果(/critical | error/){
打开(myFile,'>>parser_log.txt');
打印myFile$;
}
}
它必须是perl吗?GNUgrep
提供了在匹配行之前/之后打印指定数量的“上下文”行的选项,例如
grep --before-context=10 '(critical \| error)' parserlog.txt
使用数组。他们可以帮忙。在这里,我将其用作一种FIFO或队列:
#!/usr/bin/perl
use warnings;
use strict;
open LOG, "<", "/Users/erangross/Projects/perl/log" or die "Can't open log: $!";
open my $parseLog, '>>', 'parser_log.txt') or die "Can't open output file: $!";
my @lastTenLines;
while (<LOG>){
push @lastTenLines, $_; # add current line.
shift @lastTenLines while @lastTenLines > 10; # remove lines outside your scope.
print $parseLog @lastTenLines if /critical | error/x; # print if there is a find.
}
#/usr/bin/perl
使用警告;
严格使用;
打开日志“>”、“parser_LOG.txt”)或“die”无法打开输出文件:$!";
我的最后十行;
而(){
按@lastTenLines,$35;添加当前行。
在@lastTenLines>10时移动@lastTenLines;#删除范围外的行。
打印$parseLog@lastTenLines if/critical | error/x;#如果有查找,则打印。
}
使用。自Perl v5.7.3以来,它一直是一个核心模块,因此不需要安装
Tie::File
允许您像访问数组元素一样随机访问文件中的记录。问题简化为跟踪匹配数组的索引,并从索引小于9的位置打印所有元素
use strict;
use warnings;
use Tie::File;
open my $plog, '>', 'parser_log.txt' or die $!;
tie my @log, 'Tie::File', '/Users/erangross/Projects/perl/log' or die $!;
for my $i (0 .. $#log) {
next unless / critical | error /xi;
my $start = $i > 9 ? $i - 9 : 0;
print $plog $log[$_] for $start .. $i;
}
与相同,这是Perl:ack-b10'critical | error'/Users/erangross/Projects/Perl/log