从文件中读取一行,如果模式匹配,则在perl中从中删除它

时间:2015-03-17 09:21:03

标签: 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.

我想阅读这个文件并将这些行与模式相匹配"我想去罗马。"并省略那些与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吗?

4 个答案:

答案 0 :(得分:1)

就像

一样简单
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/;
}

答案 1 :(得分:0)

awk '$0~/I want to go Rome/' jobs.txt

答案 2 :(得分:0)

试试这个:

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.

答案 3 :(得分:0)

grep -v&#39;我想去罗马&#39; jobs.txt

写起来要简单得多。