在匹配正则表达式"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, '>>parser_log.txt');
print myFile $_;
}
}发布于 2012-07-14 23:10:55
使用数组。他们可以提供帮助。在这里,我将其用作一种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.
}发布于 2012-07-14 23:04:10
它一定要是perl吗?GNU允许您在匹配行之前/之后打印指定数量的“context”行,例如
grep --before-context=10 '(critical \| error)' parserlog.txt发布于 2012-07-15 00:06:00
使用Tie::File。从Perlv5.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;
}https://stackoverflow.com/questions/11484710
复制相似问题