我需要从两个标记点之间的文件中剪切一组线。例如,文件是
file.txt的
END
line 1 not removed
END
line 2 not removed
line 3 not removed
BEGIN
line 1 is to be removed
line 2 is to be removed
line 3 is to be removed
END
line two last not removed
END
line three last not removed
line four last not removed
我想删除BEGIN
和END
之间的行。新文件变为
FILE2.TXT
END
line 1 not removed
END
line 2 not removed
line 3 not removed
line two last not removed
END
line three last not removed
line four last not removed
这意味着BEGIN
和END
之后的第一个BEGIN
,并且应删除它们之间的行。
我能够编写这个程序,它完美无缺。但有没有更好的方法呢?
use File::Copy;
$j = $i = 0;
open(DATA, "<file1.txt");
open(DATA1, ">file2.txt");
while (<DATA>) {
if ($_ =~ /^BEGIN/) { $i = 1; }
if ($_ =~ /^END/ && $i == 1) { $i = 0; next if $_ }
if ($i == 1) { next if $_; }
print DATA1 $_;
}
close(DATA);
close(DATA1);
copy "file2.txt", "file1.txt";
答案 0 :(得分:11)
while(<DATA>) {
print DATA1 $_ unless /^BEGIN/ .. /^END/;
}
关于perldoc的范围..
运算符,
在标量上下文中,&#34; ..&#34;返回一个布尔值。运算符是双稳态的,就像一个触发器,并模拟sed,awk和各种编辑器的行范围(逗号)运算符。每个&#34; ..&#34;运算符维护自己的布尔状态,甚至调用包含它的子例程。只要其左操作数为假,它就是假的。一旦左操作数为真,范围运算符将保持为真,直到右操作数为真,此后范围运算符再次变为假。