全,
Perl有一个非常强大的特性,名为grep{} @some_var。
我要做的是修改一个脚本,以使用grep解析AIDE日志文件,并计算更改的行数。
但是,由于某种原因,计数为0。
有人能帮忙吗?我已经很久没有在生产中使用Perl了..。
#!/usr/bin/perl -w
use strict;
my @lines;
open( INFILE, "aide.log" ) || die "Cannot open input file for processing";
push( @lines, $_ ) while <INFILE>;
close INFILE;
my $matched;
my $count = grep { $matched == 1; $matched = 1 if $_ =~ /[-A-Za-z0-9]*(Added|Changed|Removed)/; $matched = 0 if $_ =~ /[-A-Za-z0-9]*Detail/ } @lines;
print "Number of changed files is ", $count, "!\n";我只需要数一数
XXX Added
XXX Changed
XXX Deleted和
XXX Detail伯爵不应该包括那些台词。
其中XXX只是一些任意的文本。
蒂娅!
编辑
aide.log
AIDE version xxx
Executed on 23 September 2019 05:15:00
2019-09-23T05:15:00+00 localhost Added files
2019-09-23T05:15:00+00 localhost /tmp/testfile
2019-09-23T05:15:00+00 localhost /scripts/aide-parser.pl
2019-09-23T05:15:00+00 localhost Changed files
2019-09-23T05:15:00+00 localhost /var/log/syslog
2019-09-23T05:15:00+00 localhost Deleted files
2019-09-23T05:15:00+00 localhost /scripts/aide-parser.pl.old
2019-09-23T05:15:00+00 localhost /etc/aide.conf.old
2019-09-23T05:15:00+00 localhost /etc/iptables.conf.old
2019-09-23T05:15:00+00 localhost Details of changes样本输出:
Number of changed files is 6只应计算带有文件名的行。
/EDIT
发布于 2019-09-24 03:02:06
实现这一目标的一种方法确实是保持状态,即你正在尝试的状态。
一个很好的工具就是距离算子。
use warnings;
use strict;
use feature 'say';
my $file = shift or die "Usage: $0 file\n";
my $beg = qr/Added|Changed|Deleted/;
my $end = qr/Detail/;
my $cnt;
open my $fh, '<', $file or die "Can't open $file: $!";
while (<$fh>) {
if (/$beg/ .. /$end/) {
++$cnt unless /$end|$beg/;
}
}
say $cnt;这将为所提供的输入文件打印6。(还保存数组上的行并检查。)
对张贴代码的评论
grep是一个过滤器,这对它不是一个好的用途-w已经被use warnings;取代了。2000年?大概20年前。不是故意嘲笑,只是请你更新一下open my $fh ...),而不是全局(INFILE)。那样好多了$matched == 1;是一个错误,它应该是= (而不是==)。$_ =~ //,因为regex的match运算符(以及替换运算符)默认使用$_。虽然对缺省值(如$_ )的依赖是可以讨论的,但在这种情况下,忽略它可以明显提高可读性,而且regex几乎总是如此。https://stackoverflow.com/questions/58070654
复制相似问题