Reputation: 83
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
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
Reputation: 1108
if ( $line =~ /regex/ ) { # If it matches this regex
<FILE>; # gobble gobble
}
Is all you need my friend.
Upvotes: 0
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
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