3

テキスト ファイルがあり、パターンで始まり特定のパターンで終わる特定の行を取得したいと考えています。例:

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);

よろしくお願いします。

4

3 に答える 3

14

スカラー範囲演算子を使用できます:

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

while (<$fh>) {
    print if /Startpattern/ .. /Endpattern/;
}
于 2011-03-22T09:32:57.737 に答える
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

開始パターンと終了パターンも出力する場合は、その if ブロックにも push ステートメントを追加します。

于 2011-03-22T11:06:15.453 に答える
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;
}
于 2011-03-22T09:35:29.987 に答える