2010-08-24 112 views
1

我有這樣 這樣的文本文件是一個垃圾線 這是垃圾LINE2 這是垃圾line3中 MESSAGE1 這是文本 的第一行,這是文本 的第二行,這是文字 此的第三行是文本 的第四行,這是文字的第五行 message1_end 下一行Perl模式匹配

我想從message1啓動模式匹配起,然後打印之間目前的案文和message1_end,之後應該停止模式匹配。

如何在perl中做到這一點?

在此先感謝

Senthil。

回答

-1

你可以這樣做:

open F,"<","input.txt" or die; # try to open the file. 
while(<F>) { # loop through each line of the file. 
     last if(/^message1_end\n$/); # break if message end is found. 
     $messsage.=$_ if($start); # append to message 
     $start = 1 if(/^message1\n$/); # set start to 1 to start appending. 
} 

print $messsage; 
3

或許這對你的作品。

open(YOURFILE,"./input.txt"); 
while (<YOURFILE>) { 
     if (/message1/ .. /message1_end/) { 
       printf "%s",$_; 
     } 
} 
close(YOURFILE); 
+0

這也打印標記,不僅它們之間的文本 – 2010-08-24 10:01:04

+0

它不適用於我 – 2010-08-24 12:05:22

+0

它是如何工作的? :-) – 2010-08-24 12:12:53

-2

另一種方法,如果輸入文件裝入內存:

#!/usr/bin/perl 

local $/=undef; 
open FILE, "input.txt" or die "Couldn't open file: $!"; 
$string = <FILE>; 
close FILE; 

print $1 if ($string =~ /message1(.*)message1_end/sm); 
3
use strict; 
use warnings; 

open my $fh, '<', 'filename' or die "can't open 'filename' for reading : $!" 
while(<$fh>) { 
    chomp; 
    if(/^message1$/ .. /^message1_end$/) { 
     print $_,"\n" unless($_ eq 'message1' or $_ eq 'message1_end'); 
    } 
} 
close $fh; 
+0

恭喜發佈使用詞法文件句柄的唯一答案,三參數打開並使用正確的錯誤處理! – Ether 2010-08-24 16:18:55

+0

@Ether:非常感謝 – Toto 2010-08-24 17:17:28

1

我不認爲我們會得到一個完美的答案,這個問題是它是如此模糊,但在這裏不用。

由於perldoc解釋,您可以使用捕獲緩衝區來簡化您的工作。 總之,你可以參考文本組(()的塊)裏面的的正則表達式與你做後的的初始化相同。您只需使用反斜槓(\)而不是美元符號($)來引用它們。

此代碼假定您具有可訪問的整個可搜索緩衝區。如果你想逐行執行,你需要有一個標記計數器(或其他類似的機制)來確保你可以處理遞歸字符串(假設你的消息塊本身可以包含消息塊)

#!/usr/bin/perl 
use warnings; 
use strict; 

my $buf = 'this is a junk line 
this is a junk line2 
this is a junk line3 
message1 
this is first line of text 
this is second line of text 
this is third line of text 
this is fourth line of text 
this is fifth line of text 
message1_end 
the next line'; 

if($buf =~m/(message\d)(.*?)(\1_end)/sg) { 
    my $message = $2; 
    # ... 
} 

這裏,\d匹配單個數字(見的perldoc鏈路)和\1計算結果爲相同$1( 「MESSAGE1」)。由於開始標記僅與「_end」不同,因此我們使用開始標記來創建我們要查找的結束標記。通過這樣做,代碼對於多個消息(「message1」,「message2」,..)可以很好地工作。