Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: how to check for a word in a file and if found remove that line, the above line and the below line from the file.

by johngg (Canon)
on Jan 20, 2016 at 11:59 UTC ( [id://1153168]=note: print w/replies, xml ) Need Help??


in reply to how to check for a word in a file and if found remove that line, the above line and the below line from the file.

Here's a slightly different approach that runs a while loop checking that end of file hasn't been reached rather than reading each line directly. Inside the loop a line is pushed onto the buffer then tested for the "reject" condition. If it is a reject then the next line is also added to the buffer then the whole buffer is discarded so as to reject all three lines. If the most recent line was not a reject then the previous line is shifted off the buffer and printed.

use strict; use warnings; open my $inFH, q{<}, \ <<EOD or die $!; XXXXX - additional test 1 XXXXX - additional test 1 ZZZZZ HHHHH - additional test 1 output expected PPPPP XXXXX is my name 1 XXXXX is my name 2 YYYYY KKKKK UUUUU BBBBB CCCCCC XXXXX is what I play KKKKK NNNNN ZZZZZ - additional test 2b XXXXX - additional test 2a QQQQQ - additional test 3 RRRRR - additional test 4 GGGGG XXXXX - additional test 5 XXXXX - additional test 5 EOD my @buffer; while ( not eof $inFH ) { push @buffer, scalar <$inFH>; if ( $buffer[ -1 ] =~ m{XXXXX} ) { last if eof $inFH; push @buffer, scalar <$inFH>; push @buffer, scalar <$inFH> while $buffer[ -1 ] =~ m{XXXXX} and not eof $inFH; @buffer = (); } else { print shift @buffer unless scalar @buffer == 1 and not eof $inFH; } } close $inFH or die $!;

The output.

HHHHH - additional test 1 output expected KKKKK UUUUU BBBBB NNNNN RRRRR - additional test 4

I hope this is of interest.

Update: Added the output.

Update: 2: Inserted push @buffer, scalar <$inFH> while ... line and added some paired "XXXXX" lines to address the point raised by mr_mischief. The output is unchanged.

Cheers,

JohnGG

  • Comment on Re: how to check for a word in a file and if found remove that line, the above line and the below line from the file.
  • Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1153168]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (7)
As of 2024-04-19 11:41 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found