perl 读取文件并抓取特定行

标签 perl file string-matching

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

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

在此先感谢您的帮助。

最佳答案

您可以使用标量 range operator :

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

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

关于perl 读取文件并抓取特定行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5389115/

相关文章:

C++:从文件中读取?

visual-studio - 这是哪种字符串匹配语言?

algorithm - 以最高分数解决拼字游戏

Perl 脚本查找 Unix 上所有无主文件和目录 - 如何进一步优化?

javascript - 我如何在 Angular 4 中像 Firefox 一样使用 chrome 选择相同的文件

Perl : Unexpected behavior with website scraping

javascript - 有没有办法更改使用输入上传文件的顺序

java - VML 路径的字符串操作

c# - 如何一次获取所有文件属性,包括作者、标题、mp3 标签等

perl - 使用 Perl 获取 <td> 值