如何跳过文件行只检索所需的中间行?

时间:2014-04-23 08:00:06

标签: perl

我有一个如下所示的txt文件:

The number of lines
on the upper part of 
this file can 
vary in size
.    :    .    :    .    :    .    :    .    :    .    :    .
lineA
lineB
lineC
_____________________________________________________________
The number of lines
on the lower part of 
this file can 
also vary in size

我想抓住

之间的所有界限
.    :    .    :    .    :    .    :    .    :    .    :    .

_____________________________________________________________

上面和下面的其他行我想忽略。如果","直到"我已经尝试了#34;和"最后"没有任何成功。关于如何做到这一点的任何想法?这是我到目前为止所做的。

open (IN, "$file") || die "Cannot open file $file";
while(my $line=<IN>) 
{
    chomp $line;
    last if ($line =~ m/:/);
    #do something with these lines
}

2 个答案:

答案 0 :(得分:2)

您可以使用.....运算符通过给出开始和结束条件来过滤掉行。

例如:

#!/usr/bin/perl

use strict;
use warnings;

while (<DATA>) {
    if (m/^\./ ... m/^_/) {
            # You may want to do more filtering at here
        print;
    } 
}

__DATA__
The number of lines
on the upper part of 
this file can 
vary in size
.    :    .    :    .    :    .    :    .    :    .    :    .
lineA
lineB
lineC
_____________________________________________________________
The number of lines
on the lower part of 
this file can 
also vary in size

输出:

$ perl t.pl
.    :    .    :    .    :    .    :    .    :    .    :    .
lineA
lineB
lineC
_____________________________________________________________

答案 1 :(得分:2)

use strict;
use warnings;

open (my $IN, "<", $file) || die $!;
while (my $line = <$IN>)
{
    chomp $line;
    # force 0 instead of empty string 
    # so it can be used to numerically compare under warnings
    my $switch = ($line =~ /:/ .. $line =~ /__/) ||0;

    next if $switch <=1;
    last if $switch =~ /E/;

    #do something with these lines

}

$switch

1   # starting with /:/ line
2   # lineA
3   # lineB
4   # lineC
5E0 # ending with /__/ line

所以我们想要1之后的所有行,并在匹配/E/时结束while循环