如何在Perl中匹配行之后抓取多行? [英] How can I grab multiple lines after a matching line in Perl?

查看:279
本文介绍了如何在Perl中匹配行之后抓取多行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在逐行分析Perl中的一个大文件(以\ n终止),但是当我到达某个关键字(说"TARGET")时,我需要抓住TARGET和下一个完全之间的所有行空行.

I'm parsing a large file in Perl line-by-line (terminated by \n), but when I reach a certain keyword, say "TARGET", I need to grab all the lines between TARGET and the next completely empty line.

因此,给定文件的一部分:

So, given a segment of a file:

第1行
第2行
第3行
第4行目标
5号线抓住这条线
第6行抓住这行
\ n

Line 1
Line 2
Line 3
Line 4 Target
Line 5 Grab this line
Line 6 Grab this line
\n

应变为:
第4行目标
第5行抓住这行
第6行抓住这一行

It should become:
Line 4 Target
Line 5 Grab this line
Line 6 Grab this line

我遇到麻烦的原因是我已经逐行处理了文件;如何在解析过程中途更改定界?

The reason I'm having trouble is I'm already going through the file line-by-line; how do I change what I delimit by midway through the parsing process?

推荐答案

您想要这样的东西:

my @grabbed;
while (<FILE>) {
    if (/TARGET/) {
        push @grabbed, $_;
        while (<FILE>) {
            last if /^$/;
            push @grabbed, $_;
        }
    }
}

这篇关于如何在Perl中匹配行之后抓取多行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆