在Perl , 如何从当前位置(最后一次替换的位置)到一行的末尾替换一个模式?
我在一行中完成了所有这些替换:
...
s/\[//;
s/(\/\w\w\w\/)/ getMonth $1 /e;
s/:/ /;
s/\s\+\d\d\d\d\]//;
#NOW: replace all blanks with a plus sign from this position until the end of this line.
最佳答案
我看到你已经接受了一个答案。但是,对于手头的任务,使用 Apache::ParseLog 会更合适。或者也许 Apache::LogRegex :
Apache::LogRegex
- Parse a line from an Apache logfile into a hash
在我看来,您正在尝试从头开始编写日志文件分析器,这是您按月对日志文件条目进行分组的方式。如果是这样,请停止重新发明方轮。
即使您不想使用外部模块,您也可以通过使用split 分而治之来简化任务。 :
#!/usr/bin/perl
use strict; use warnings;
use Carp;
use Regex::PreSuf;
my @months = qw(jan feb mar apr may jun jul aug sep oct nov dec);
my %months = map { $months[$_] => sprintf '%02d', $_ + 1 } 0 .. 11;
my $months_re = presuf( @months );
# wrapped for formatting, does not make any difference
my $str = q{62.174.188.166 - - [01/Mar/2003:00:00:00 +0100] "GET
/puntos/img/ganar.gif HTTP/1.1" 200 1551
"http://www.universia.com/puntos/index.jsp";
"Mozilla/4.0 (compatible; MSIE 5.0; Windows 98; DigExt; Hotbar 2.0)"};
chomp($str);
my @parts = split qr{\s\[|\]\s}, $str;
if ( $parts[1] =~ m! / ($months_re) / !ix ) {
$parts[1] = $1;
}
$parts[2] =~ s/\s/+/g;
print join(' ', @parts), "\n";
输出:
62.174.188.166 - - Mar "GET+/puntos/img/ganar.gif+HTTP/1.1"+200+1551+"http://www
.universia.com/puntos/index.jsp";+"Mozilla/4.0+(兼容;+MSIE+5.0;+Windows+98
;+DigExt;+Hotbar+2.0)"
关于regex - Perl:从当前位置替换模式直到行尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1737413/