Regex 从文件中读取一行,如果模式匹配,则在perl中将其删除
我有一个文件place.txt,内容是:Regex 从文件中读取一行,如果模式匹配,则在perl中将其删除,regex,perl,Regex,Perl,我有一个文件place.txt,内容是: I want to go Rome. Will Go. I want to go Rome. Will Not Go. I want to go Rome. Will Not Go. I want to go Rome. Will Go. I want to go India. Will Not Go. I want to go India. Will Not Go. I want to go Rome. Will Go. 我想读一下这个文件,把这些线
I want to go Rome. Will Go.
I want to go Rome. Will Not Go.
I want to go Rome. Will Not Go.
I want to go Rome. Will Go.
I want to go India. Will Not Go.
I want to go India. Will Not Go.
I want to go Rome. Will Go.
我想读一下这个文件,把这些线和我想去罗马的图案匹配起来。并在perl中省略与此文件中的模式匹配的行
我的示例代码是:
$file = new IO::File;
$file->open("<jobs.txt") or die "Cannot open jobs.txt";
while(my $line = $file->getline){
next if $line =~ m{/I want to go Rome/};
print $line;
}
close $file;
注意:我的文件会很大。我们可以使用sed或awk吗?它非常简单
awk '$0~/I want to go Rome/' jobs.txt
perl -ine'print unless /I want to go Rome/'
如果你喜欢脚本
use strict;
use warnings;
use autodie;
use constant FILENAME => 'jobs.txt';
open my $in, '<', FILENAME;
while (<$in>) {
if ( $. == 1 ) { # you need to do this after read first line
# $in will keep i-node with the original file
open my $out, '>', FILENAME;
select $out;
}
print unless /I want to go Rome/;
}
试试这个:
use strict;
use warnings;
use File::Copy;
open my $file, "<", "jobs.txt" or die "Cannot open jobs.txt : $!";
open my $outtemp, ">", "out.temp" or die "Unable to open file : $!\n"; # create a temporary file to write the lines which doesn't match pattern.
while(my $line = <$file>)
{
next if $line =~ m/I want to go Rome/; # ignore lines which matches pattern
print $outtemp $line; # write the rest lines in temp file.
}
close $file;
close $outtemp;
move("out.temp", "jobs.txt"); # move temp file into original file.
grep-v“我想去罗马”jobs.txt
写起来更简单。问题可能是双括号。使用m{…}或m/../或/../但不能使用m{/../}。它尝试查找包含“/”的模式。如何在此perl文件中使用awk在模式匹配后更新同一文件。如何从file@user3616128:您不能在文件中打洞,因此您必须将文件的其余部分向前移动以填补漏洞,或者最好是复制。我认为这个答案可能是对它所做的做了一些解释,这一点有所改进。@user3616128:我不使用awk,在perl中,请看一看已编辑的代码。