【问题标题】:perl reading file and grabbing specific linesperl 读取文件并获取特定行
【发布时间】:2011-07-20 08:01:34
【问题描述】:

我有一个文本文件,我想抓取以特定模式开始并以特定模式结束的特定行。 示例:

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

提前感谢您的帮助。

【问题讨论】:

  • 我深知,当您写“无法打开日志文件。”时,您的意思是写“无法打开 $LOGFILE:$!”。

标签: perl file string-matching


【解决方案1】:

您可以使用标量range operator

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

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

【讨论】:

  • 嗨,这听起来不错,但我有多个具有开始和结束模式的组。
  • @Tester: 标量 .. 应该适用于文件中任意数量的组
【解决方案2】:

这样的?

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

【讨论】:

  • 不幸的是,它只打印与 startpattern 匹配的行。我需要打印 startpattern、start 和 endpattern 之间的文本以及 endpattern。我有多个包含 startpattern、text、text、text、endpattern 的组
  • 对不起,我的错误。我忘了删除一行。如何将这些条目分组到几个数组中?
  • 我也在做类似的事情,但是 eugene-y 提到的解决方案也打印了我们不想要的 startpattern 和 end pattern ,我们如何否定它们,请建议。
【解决方案3】:

这个怎么样:

#!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 语句。

【讨论】:

  • 完美。非常感谢。现在我只有一个问题 :-) 我如何设置动态数组名并在将所有匹配的行放入其中后打印每个数组?
  • 我自己对 perl 还很陌生,我不太明白这个问题。如果您能更详细地说明您的要求,我可能会提供帮助。
猜你喜欢
  • 2014-07-25
  • 1970-01-01
  • 2014-07-29
  • 2012-01-22
  • 2013-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-02
相关资源
最近更新 更多