【问题标题】:read a line from file and if pattern match then delete it from it in perl从文件中读取一行,如果模式匹配,则在 perl 中将其删除
【发布时间】:2015-03-18 02:26:56
【问题描述】:

我有一个文件 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 吗?

【问题讨论】:

  • 问题可能是双括号。使用m{...}m/...//.../,但不要使用m{/.../}。它尝试查找包含“/”的模式。

标签: regex perl


【解决方案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/;
}

【讨论】:

    【解决方案2】:

    grep -v '我想去罗马'jobs.txt

    写起来还是简单多了。

    【讨论】:

      【解决方案3】:
      awk '$0~/I want to go Rome/' jobs.txt
      

      【讨论】:

        【解决方案4】:

        试试这个:

        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.
        

        【讨论】:

        • 如何在这个perl文件中使用awk在模式匹配后更新同一个文件。
        • 如何从文件中删除匹配模式的行
        • @user3616128:你不能在文件中打洞,所以你必须向前移动文件的其余部分来填补洞,或者更好地制作副本。
        • 我认为这个答案可能会通过更多解释来改进。
        • @user3616128 :我不使用awk,在perl 中查看编辑后的代码。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-23
        • 2017-06-12
        • 1970-01-01
        相关资源
        最近更新 更多