L
learner
Hi, all,
I 've searched high and low, just couldn't find a single decent
example to replace multiple lines from a file.
So I did this:
#!/usr/local/bin/perl
undef $/;
$original = "
// This is an old text
// that is across several
// lines in this file. This file
// also contains the copy right
// symbol \251.";
$replacement = "
// I just want to replace
// the old lines in one fell
// swoop!";
$sHOME = "./changed/";
foreach $file (@ARGV) {
if (! open(INPUT,"<$file") ) {
print "Can't open input file $file\n";
next;
}
$data=<INPUT>;
close INPUT;
if ($data =~ s/$original/$replacement/g) {
$newfile = $sHOME.$file;
print $newfile."\n";
if (! open(OUTPUT,">$newfile") ) {
die "Can't open output file $newfile\n";
}
print OUTPUT $data;
close OUTPUT;
print "$file changed\n";
}
else { print "$file not changed\n"; }
}
exit(0);
Then I would do:
perl thisperlfile.pl name.of.file.with.original.txt
The input file contains only one copy of the original text, but it
created more than 50 replacement txt in the final file. I am really
puzzled. Could someone help please? Thanks.
I 've searched high and low, just couldn't find a single decent
example to replace multiple lines from a file.
So I did this:
#!/usr/local/bin/perl
undef $/;
$original = "
// This is an old text
// that is across several
// lines in this file. This file
// also contains the copy right
// symbol \251.";
$replacement = "
// I just want to replace
// the old lines in one fell
// swoop!";
$sHOME = "./changed/";
foreach $file (@ARGV) {
if (! open(INPUT,"<$file") ) {
print "Can't open input file $file\n";
next;
}
$data=<INPUT>;
close INPUT;
if ($data =~ s/$original/$replacement/g) {
$newfile = $sHOME.$file;
print $newfile."\n";
if (! open(OUTPUT,">$newfile") ) {
die "Can't open output file $newfile\n";
}
print OUTPUT $data;
close OUTPUT;
print "$file changed\n";
}
else { print "$file not changed\n"; }
}
exit(0);
Then I would do:
perl thisperlfile.pl name.of.file.with.original.txt
The input file contains only one copy of the original text, but it
created more than 50 replacement txt in the final file. I am really
puzzled. Could someone help please? Thanks.