1

即使该行以 * 开头,我的代码也会尝试提取范围这是我的代码:

while (<FILE1>) {

    $_ =~ s/^\s+//; #remove leading spaces
    $_ =~ s/\s+$//; #remove trailing spaces

    if (/IF/ .. /END-IF/) {

        if($_ =~ m/END-IF/) {

            $flag = 1;
        }
        print FINAL "$_\n";

        if ($flag == 1) {

            $flag = 0;
            print FINAL "\n\n";
        }
    }
}
close FINAL;
close FILE1;

我的最终输出文件应该只包含所有 IF 和 END-IF 之间的范围,由 \n\n 分隔,如果 IF 块中有一个 IF,则从第一个 if 到第二个 IF 之前的行的范围应该是保存在 FINAL 中,由 \n\n 分隔

4

3 回答 3

2

如果要排除 IF 和 END-IF,请使用以下命令:

perl -lne 'if(/IF/.../END-IF/ and $_!~/^\*|IF|END-IF/){print}' your_file

如果要包含 IF 和 END-IF,请使用以下命令:

perl -lne 'if(/IF/.../END-IF/ and $_!~/^\*/){print}' your_file
于 2012-09-17T06:17:58.420 回答
0

添加下一行解决了我的问题:)

next if(/^\*/);
于 2012-09-17T05:41:21.210 回答
0

也许以下内容会有所帮助:

use strict;
use warnings;

while (<DATA>) {
    if ( /IF/ .. /END-IF/ ) {
        next if /^\*|IF|END-IF/;
        print;
    }
}

__DATA__
This is a line.
And another line...
IF
1. A line within the if
* 2. An asterisk line within the if
3. And now, another line within the if
END-IF
Outside an if construct.
Still outside the if construct.
IF
4. A line within the if
* 5. An asterisk line within the if
6. And now, another line within the if
END-IF

输出:

1. A line within the if
3. And now, another line within the if
4. A line within the if
6. And now, another line within the if

范围内的行IF .. END-IF有条件地通过,然后仅在它们不以 or 开头*或不包含IFor时打印END-IF

于 2012-09-17T05:47:21.003 回答