Another perl Q.
Dpk
dpk@egr.msu.edu
Wed, 10 Jan 2001 13:42:20 -0500
On Tue, Jan 09, 2001 at 11:47:29AM -0500, Sean wrote:
Is there a library function or what is the best way to replace the
contents of a file between two markers with perl of course =)
like:
<!-- beginning -->
Replace all of this crap with new contents.
from the This_might_be_better.txt file
<!--end -->
Example solution is below. Execution without arguments will return
the usage. You could easily turn this into a subroutine if needed.
dpk
---- Begin script ----
#!/usr/bin/perl -w
use strict;
my $file = shift;
my $ifile = shift;
if (! $file || ! -f $file || ! $ifile || ! -f $ifile) {
print "Usage: $0 [file] [file-to-insert]\n";
exit 1;
}
open(FILE, "< $file") or die "E: Cannot open file: $file\n";
my @lines = <FILE>;
close FILE;
rename($file, "$file.bak") or die "E: Cannot backup file: $file\n";
my $flag = 0;
open(FILE, "> $file") or die "E: Cannot open file: $file\n";
for (@lines) {
if (/^<!-- beginning -->/) {
$flag = 1;
print FILE;
if (open(INSERT, "< $ifile")) {
print FILE <INSERT>;
close INSERT;
}
}
elsif (/^<!--end -->/) {
$flag = 0;
}
print FILE if $flag == 0;
}
close FILE;
---- End script ----