我的代码尝试提取范围,即使该行以*开头,这是我的代码:
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;
我的FINAL输出文件应该只包含所有IF和END-IF分隔的范围\ n \ n AND如果IF块中有IF,则范围从第一个if到第二个之前的行开始IF应保存在FINAL中,由\ n \ n
分隔答案 0 :(得分: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
答案 1 :(得分:0)
添加下一行解决了我的问题:)
next if(/^\*/);
答案 2 :(得分: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
范围内的行,只有当它们不以*
开头或包含IF
或END-IF
时才打印。