Possible Duplicate:
How to replace a string in an existing file in Perl?
I need to create a subroutine that does a search and replace in file.
Here's the contents of myfiletemplate.txt:
CATEGORY1=youknow_<PREF>
CATEGORY2=your/<PREF>/goes/here/
Here's my replacement string: ABCD
I need to replace all instances of <PREF>
to ABCD
A one liner:
perl -pi.back -e 's/<PREF>/ABCD/g;' inputfile
Quick and dirty:
#!/usr/bin/perl -w
use strict;
open(FILE, "</tmp/yourfile.txt") || die "File not found";
my @lines = <FILE>;
close(FILE);
foreach(@lines) {
$_ =~ s/<PREF>/ABCD/g;
}
open(FILE, ">/tmp/yourfile.txt") || die "File not found";
print FILE @lines;
close(FILE);
Perhaps it i a good idea not to write the result back to your original file; instead write it to a copy and check the result first.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With