in reply to Re: delete above matching line?
in thread delete above matching line?

Reading the file into a string did the trick, thanks.

{ local $/ = undef ; open TEST,'test' or die "Denied: $!\n" ; my $string = <TEST> ; close TEST ; $string =~ s/\n\nstart_of_block.*?};//s ; print $string ; }

Replies are listed 'Best First'.
Re^3: delete above matching line?
by happy.barney (Friar) on Jul 01, 2010 at 08:19 UTC
    For bigger files:
    my @out; my $print = 1; while (<>) { if (m/^start_of_block/) { $print = 0; pop @out if @out and $out[-1] eq $/; # removes previous empty line } push @out, $_ if $print; if (m/^};/) { $print = 1; } print shift @out if $print and 1 < @out; } # UPDATE: based on oldmanwillow reply: # print @out; print @out if $out[-1] =~ /^\s*$/ ;

      This almost works, and I like it much better than reading the whole file into a string. Thanks!

      The only problem is that as it is, the script leaves a trailing newline if the deleted block is the last in the file. Probably my fault for not specifying that the blocks run to the end of the file.

      The fix is simply to change the last

      print @out ;

      to

      print @out if $out[-1] =~ /^\s*$/ ;