2011-03-22 24 views
3

我有一個文本文件,我想抓住特定的行,以模式開始並以特定模式結束。 示例:perl讀取文件並抓取特定行

Text 
Text 
Startpattern 
print this line 
Print this line 
print this line 
Endpattern 
Text 
Text 
Text 

此外,還應打印起始圖案和結束圖案。我的第一次嘗試不是很成功:


my $LOGFILE = "/var/log/logfile"; 
my @array; 
# open the file (or die trying) 

open(LOGFILE) or die("Could not open log file."); 
foreach $line() { 
    if($line =~ m/Sstartpattern/i){ 
    print $line; 
    foreach $line2() { 
     if(!$line =~ m/Endpattern/i){ 
     print $line2; 
     } 
    } 
    } 
} 
close(LOGFILE); 

在此先感謝您的幫助。

+1

我知道內心深處,當你寫下「無法打開日誌文件」時,你的意思是寫「無法打開$ LOGFILE:$!」。 – 2011-03-22 09:34:43

回答

2

如何:

#!perl -w 
use strict; 

my $spool = 0; 
my @matchingLines; 

while (<DATA>) { 
    if (/StartPattern/i) { 
     $spool = 1; 
     next; 
    } 
    elsif (/Endpattern/i) { 
     $spool = 0; 
     print map { "$_ \n" } @matchingLines; 
     @matchingLines =(); 
    } 
    if ($spool) { 
     push (@matchingLines, $_); 
    } 
} 

__DATA__ 

Text 
Text 
Startpattern 
print this line 
Print this line 
print this line 
Endpattern 
Text 
Text 
Text 
Startpattern 
print this other line 
Endpattern 

如果你也想打印的開始和結束模式,加推聲明中,如果塊爲好。

+0

完美。非常感謝你。現在我只有一個問題:-)我怎樣才能設置動態數組名和打印每個數組後,我抓住了所有匹配的線? – Stefan 2011-03-22 12:14:42

+0

我對Perl本人相當陌生,而且我不太明白這個問題。如果你可以更詳細地解釋你的要求是什麼,我可能會提供幫助。 – Bee 2011-03-23 02:43:38

14

您可以使用標range operator

open my $fh, "<", $file or die $!; 

while (<$fh>) { 
    print if /Startpattern/ .. /Endpattern/; 
} 
+0

嗨,這聽起來不錯,但我有多組開始和結束模式。 – Stefan 2011-03-22 09:41:49

+2

@Tester:標量'..'應該適用於文件中的任意數量的組 – 2011-03-22 10:05:28

1

像這樣的事情?

my $LOGFILE = "/var/log/logfile"; 
open my $fh, "<$LOGFILE" or die("could not open log file: $!"); 
my $in = 0; 

while(<$fh>) 
{ 
    $in = 1 if /Startpattern/i; 
    print if($in); 
    $in = 0 if /Endpattern/i; 
} 
+0

不幸的是只打印與startpattern匹配的行。我需要打印startpattern,開始和結束模式之間的文本以及結束模式。我有多個組,包括startpattern,文本,文本,文本,結尾模式 – Stefan 2011-03-22 09:54:06

+0

@Tester:你確定嗎?似乎適合我:http://pastebin.com/nyfGr0my – jho 2011-03-22 10:01:15

+0

對不起,我的錯誤。我忘了刪除一行。我怎樣才能將這些條目分成幾個數組? – Stefan 2011-03-22 10:18:19