Perl脚本:对日志文件进行排序。

时间:2016-05-20 19:15:28

标签: perl scripting grep

尝试编写一个脚本,该脚本打开一个目录并逐行读取多个日志文件,并搜索以下信息:  “出勤率= 0”以前我使用grep "Attendance =" *来搜索我的信息,但尝试编写脚本来搜索我的信息。 需要你的帮助才能完成这项任务。

  #!/usr/bin/perl

  use strict;
  use warnings;
  my $dir = '/path/';
  opendir (DIR, $dir) or die $!;
  while (my $file = readdir(DIR))
   {
   print "$file\n";
   }
   closedir(DIR);
   exit 0;

2 个答案:

答案 0 :(得分:1)

你的perl经历是什么?

我假设每个文件都是文本文件。我会给你一个提示。试着找出放置此代码的位置。

# Now to open and read a text file.
my $fn='file.log';
# $! is a variable which holds a possible error msg.
open(my $INFILE, '<', $fn) or die "ERROR: could not open $fn. $!";
my @filearr=<$INFILE>; # Read the whole file into an array.
close($INFILE);

# Now look in @filearr, which has one entry per line of the original file.

exit; # Normal exit

答案 1 :(得分:0)

我更喜欢使用File::Find::Rule来做这样的事情。它保留了路径信息,并且易于使用。这是一个做你想做的事的例子。

use strict;
use warnings;

use File::Find::Rule;

my $dir = '/path/';
my $type = '*';

my @files = File::Find::Rule->file()
                            ->name($type)
                            ->in(($dir));

for my $file (@files){

    print "$file\n\n";

    open my $fh, '<', $file or die "can't open $file: $!";

    while (my $line = <$fh>){
        if ($line =~ /Attendance =/){
            print $line;
        }
    }
}
相关问题