2016-05-20 66 views
-1

試圖編寫一個腳本,它打開一個目錄並逐行讀取一堆多個日誌文件並搜索信息,例如: 「Attendance = 0」以前我用grep "Attendance ="*來搜索我的信息,但試圖寫一個腳本來搜索我的信息。 需要您的幫助才能完成此任務。Perl腳本:通過日誌文件進行排序。

#!/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; 
+0

首先,使用空格和空行來顯示代碼的結構。當你要求幫助時,發佈這樣的代碼有點不禮貌。你沒有注意到你的程序看起來不像你看到的其他程序的大部分嗎?查看[perldoc perlstyle](http://perldoc.perl.org/perlstyle.html)瞭解大多數人關注的規則。 – Borodin

回答

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; 
     } 
    } 
} 
+1

您不需要雙圓括號:' - > in($ dir)'是可以的。 –

+0

非常感謝@stevieb –

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