【问题标题】:Perl Script: sorting through log files.Perl 脚本:对日志文件进行排序。
【发布时间】:2016-09-18 04:00:36
【问题描述】:

尝试编写一个脚本,该脚本打开一个目录并逐行读取多个日志文件并搜索信息,例如: "Attendance = 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;

【问题讨论】:

  • 首先,使用空格和空行来显示代码的结构。当您寻求帮助时发布这样的代码有点粗鲁。你没有注意到你的程序看起来不像你看到的大多数其他程序吗?看看perldoc perlstyle 了解大多数人遵循的规则。

标签: perl scripting grep


【解决方案1】:

我更喜欢将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;
        }
    }
}

【讨论】:

  • 你不需要双括号:-&gt;in($dir) 就可以了。
【解决方案2】:

你的 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-02
    • 1970-01-01
    • 1970-01-01
    • 2021-10-28
    • 2013-12-06
    • 2018-10-07
    • 2011-04-04
    • 1970-01-01
    相关资源
    最近更新 更多