开发者

Perl - Searching a file for specific text and deleting a range of lines [duplicate]

开发者 https://www.devze.com 2023-02-12 15:46 出处:网络
This question already has an answer here: Closed 11 years ago. Possible Duplicate: How do I change, delete, or insert a line in a file, or append to the beginning of a file in Perl?
This question already has an answer here: Closed 11 years ago.

Possible Duplicate:

How do I change, delete, or insert a line in a file, or append to the beginning of a file in Perl?

开发者_StackOverflow

How would I use perl to open up a file, look for an item that someone inputs, and if it is found, it will delete from that line to 14 lines below.


Something like this will work:

#!/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;
$|++


#!/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;
0

精彩评论

暂无评论...
验证码 换一张
取 消