简体   繁体   English

perl读取文件并抓取特定的行

[英]perl reading file and grabbing specific lines

I have a text file and I want to grab specific lines starting with a pattern and ending with a specific pattern. 我有一个文本文件,我想抓住以模式开头并以特定模式结束的特定行。 Example: 例:

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

Also the start pattern and the end pattern should be printed. 还应打印开始图案和结束图案。 My first try was not really successful: 我的第一次尝试并没有真正成功:


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

Thanks in advance for your help. 在此先感谢您的帮助。

You can use the scalar range operator : 您可以使用标量范围运算符

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

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

How about this: 这个怎么样:

#!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 you want the start and end patterns to also be printed, add the push statements in that if block as well. 如果您还希望打印开始和结束模式,请在该if块中添加push语句。

Something like this? 像这样的东西?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM