0

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

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.

Community
  • 1
  • 1
  • I have tried toying around with the sed command, but I cant get it to pass in variables and it doesnt actually save to the file, it only outputs the results. I am beginner in perl – Tristan Smith Feb 21 '11 at 18:00

2 Answers2

1

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;
$|++
BadFileMagic
  • 701
  • 3
  • 7
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;
Brad Gilbert
  • 33,846
  • 11
  • 78
  • 129