Scranton
Scranton

Reputation: 339

In-place deletion of a block of lines already found in a file using perl

I want to be able to locate a block of lines in a file determined by start and end keywords and then delete this block. I am using "if (/START/../END/)" to locate this block, but am not sure how to delete the lines in this block. What statement can I use inside the 'if' above to achieve this?

Note: It does not have to be true deletion. I mean, it can be simply replace the line with empty space.

PS: I am a first-time perl user and pardon me if this seems to be a stupid question. I know there are MANY similar questions out there, but no one seems to be dealing with in-place deletion and suggest options like print entire file to another file excluding the desired block.

Upvotes: 1

Views: 80

Answers (3)

perreal
perreal

Reputation: 97948

With sed:

sed '/START/,/END/d' input_file

to modify the original file:

sed -i '/START/,/END/d' input_file

Upvotes: 1

mob
mob

Reputation: 118605

Perl makes this pretty easy.

One line, in place deletion of lines between pattern1 and pattern2:

perl -i -ne 'print unless /pattern1/../pattern2/' input_file

See perlrun to understand perl's various command-line switches

Upvotes: 4

toolic
toolic

Reputation: 62037

You could just invert your logic:

use warnings;
use strict;

while (<DATA>) {
    print unless /START/ .. /END/;
}

=for output

foo
bar

=cut


__DATA__
foo
START
goo
END
bar

Upvotes: 2

Related Questions