neemie
neemie

Reputation: 83

how to delete the line after a regex match in Perl

I would like to delete the line after a regex match but I'm unsure how to code for deleting the next line in Perl - help?

while ( my $line = <FILE> ) {
if ($line =~ m/(regex)/i) {
# delete the next $line
}    

Upvotes: 0

Views: 2674

Answers (4)

Pavel
Pavel

Reputation: 91

You can run $> perl -pi -e 'BEGIN{undef $/;} s#(YOUR_REGEX_PATTERN)[^\n]*\n[^\n]*\n#$1\n#' YOUR_FILE

This is able to do a multiline replacement by forcing Perl to read the entire file at once. But be always sure to make a backup first! You may let Perl do it for you by appending a suffix to that -i switch like $> perl -pi.bak -e ...

Upvotes: 0

terary
terary

Reputation: 1108

if ( $line =~ /regex/ ) {  # If it matches this regex
    <FILE>;  # gobble gobble
}

Is all you need my friend.

Upvotes: 0

martingrayson
martingrayson

Reputation: 11

What about having a $skip_flag that you set when you come across a match? As you're reading your file line by line, you could build an output string, skipping lines when the flag is set.

Upvotes: 0

Andy Lester
Andy Lester

Reputation: 93795

What do you mean "delete"? You mean ignore it?

while ( my $line = <FILE> ) {
    if ( $line =~ /regex/ ) {  # If it matches this regex
        my $ignored = <FILE>;  # read the next line and ignore it.
    }
}

Upvotes: 6

Related Questions