in reply to Parsing file and removing a section

Here's a technique I use: open the original file and a new file (the latter for writing). loop through the original file. If the incoming line matches the pattern you're looking for, set a flag to true. Print the incoming line to the outgoing file unless the flag is set. Then, check to see if the line matches the pattern that ends the block you're cutting out. If so, set the flag back to false. If you don't have an explicit ending line (e.g. here you've got a nice XMLish closing tag, but you might have a file like:

Server a.b.c.d
 line 1
 line 2
Server e.f.g.h
 line 1

You can monkey with the inner logic of the loop to deal with such situations, but that's left as an exercise for the reader =)

open OLD, $oldfile or die; open NEW, "> $oldfile.new" or die; my $flag = 0; while (<OLD>) { $flag =1 if /pattern/; print NEW unless $flag; $flag = 0 if /end_pattern/; } rename ("$oldfile", "$oldfile.old") or die; rename ("$oldfile.new", $oldfile) or die;

Of course, you'd replace my dies with more helpful messages, and substitute real patterns for mine.

HTH

Philosophy can be made out of anything. Or less -- Jerry A. Fodor

Replies are listed 'Best First'.
Re: Re: Parsing file and removing a section
by petral (Curate) on Mar 08, 2001 at 02:09 UTC
    Looks like brendonc needs to see if the _next_ line matches. So maybe
    $flag =1 if /pattern/; print NEW $lastln unless $flag; $lastln = $_; if ($flag and /end_pattern/) { $lastln = ''; $flag = 0; }
    ?

    p