Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex 多次从多个文件中删除多行_Regex_Perl - Fatal编程技术网

Regex 多次从多个文件中删除多行

Regex 多次从多个文件中删除多行,regex,perl,Regex,Perl,我有几个文件(*.txt)需要从中删除行。这些文件如下所示: This is a line to keep. keep me too START some stuff to remove other to remove END keep me! This is a line to keep. keep me too keep me! 我希望他们看起来像这样: This is a line to keep. keep me too START some stuff to remove othe

我有几个文件(
*.txt
)需要从中删除行。这些文件如下所示:

This is a line to keep.
keep me too
START
some stuff to remove
other to remove
END
keep me!
This is a line to keep.
keep me too
keep me!
我希望他们看起来像这样:

This is a line to keep.
keep me too
START
some stuff to remove
other to remove
END
keep me!
This is a line to keep.
keep me too
keep me!
我已经走了这么远:

perl -i -p0e 's/#START.*?END/ /s' file.txt

这将从
file.txt
中删除该文件的第一个实例,但我不知道如何从
file.txt
中删除所有实例(然后如何将其应用于所有
*.txt
文件?

如果显示的内容适用于第一个实例,则需要添加
/g
标志来执行所有实例,和一个shell glob来挑选所有.txt文件:

perl -i -p0e 's/#START.*?END/ /gs' *.txt

这似乎是正确的

它也可以写为一行:

perl -n -e 'print unless (/^START/ .. /^END/);' input.txt > output.txt
或者,要在位编辑文件,请执行以下操作:

perl -n -i -e 'print unless (/^START/ .. /^END/);' *.txt

这里需要注意的簿记事项是打开和写入单个文件。处理本身由处理程序处理

使用警告;
严格使用;
我的@files=@ARGV;
我的($fh_in,$fh_out);
foreach my$文件(@files)
{
my$outfile=“new_$file”;

在中打开$fh_,'这很简单,但它必须是一行吗?文件应该就地更改,还是编写新文件,还是只需要一个大文件作为输出?谢谢@zdim不,它不必是一行。我不在乎它们是否在原地更改,我想要单个文件作为输出。谢谢。我已经尝试添加了他以前有
/g
标志,但它只是删除了所有文件中的所有内容。不过,这很有效,所以我以前一定做了错事。非常感谢!@casimirithippolyte你是对的。谢谢。更新了我的答案。
use warnings;
use strict;

my @files = @ARGV;

my ($fh_in, $fh_out);

foreach my $file (@files) 
{
    my $outfile = "new_$file";

    open $fh_in, '<', $file  or die "Can't open $file: $!";
    open $fh_out, '>', $outfile  or die "Can't open $outfile: $!";

    print "Processing $file, writing to $outfile.\n";

    while (<$fh_in>) {
        print $fh_out $_ if not /^START$/ .. /^END$/;
    }
}