Perl - 在文件中搜索特定文本并删除一系列行

时间:2011-02-21 16:44:12

标签: perl

  

可能重复:
  How do I change, delete, or insert a line in a file, or append to the beginning of a file in Perl?

我如何使用perl打开文件,查找某人输入的项目,如果找到,它将从该行删除到以下14行。

2 个答案:

答案 0 :(得分:1)

这样的事情会起作用:

#!/usr/bin/env perl
use Modern::Perl;
use IO::File;

say "Enter a pattern please: ";
chomp (my $input = <>);
my $pattern;
# check that the pattern is good
eval {
    $pattern = qr ($input);
}; die $@ if $@;

my $fh = IO::File->new("test.txt", "+<") or die "$!\n";
my @lines = $fh->getlines;
$fh->seek(0,0);
for (my $pos = 0; $pos < $#lines; ++$pos) {
    if ($lines[$pos] =~ $pattern) {
        $pos += 14;
    } else {
        print {$fh} $lines[$pos];
    }
}
$fh->close;
$|++

答案 1 :(得分:1)

#!/usr/bin/env perl
use strict;
use warnings;
use autodie;

my $filename = 'filename.txt';
my $tmp = 'filename.txt.tmp';

print "Enter a pattern please: ";
chomp (my $input = <>);
my $pattern = qr($input)x;

open my $i_fh, '+<', $filename;
open my $o_fh, '>',  $tmp;

while(<$i_fh>){
  # move print here if you want to print the matching line
  if( /$pattern/ ){
    <$i_fh> for 1..14;
    next;
  }
  print {$o_fh} $_ ;
}

close $o_fh;
close $i_fh;

use File::Copy

move $tmp, $filename;