Reputation: 1490
Is there a way to replace instances of a string beginning with START and ending with END in a file, across multiple lines, in perl?
i.e. input:
good
START
bad
bad
END
good
Then find the range from START to END, and replace with 'replaced':
good
replaced
good
Thanks very much.
Upvotes: 0
Views: 101
Reputation: 902
This is a simple Perl program which replaces the strings between START and END (Case insensitive) as shown in the below code:
#!/usr/bin/perl
use strict;
use warnings;
my $InFile = $ARGV[0];
my $document = do {
local $/ = undef;
open my $fh, "<", $InFile or die "Error: Could Not Open File $InFile: $!";
<$fh>;
};
$document =~ s/\bSTART\b.*?\bEND\b/replaced/isg;
print $document;
Upvotes: 0
Reputation: 50637
You can use flip-flop ..
operator:
perl -pe '$_ = $i == 1 ? "replaced$/" : "" if $i = /START/ .. /END/' file
$i
count lines from START
to END
, or it holds false value when outside start-end block.
Upvotes: 2
Reputation: 241748
Use a flag. Something like the following:
perl -ne '$inside = print "replaced\n" if /START/;
print unless $inside;
undef $inside if /END/' file
Upvotes: 2