Hopefully this will be easy enough to solve. I have a text file with tags such as <!--mydir-->. I need to write a script to open the file and replace all occurrences of
<!--mydir--> with a variable value $mydir.
I know this should be easy to do but when I try it, it i get some strange results.
Can anyone give me a simple substitution script
Thank you
Simple perl substition
Moderator: General Moderators
Re: Simple perl substition
From the subject I assume you want that in Perl.ozmodiar wrote:Hopefully this will be easy enough to solve. I have a text file with tags such as <!--mydir-->. I need to write a script to open the file and replace all occurrences of
<!--mydir--> with a variable value $mydir.
Can anyone give me a simple substitution script
The following snippet should do it.
Code: Select all
# read the file into memory
open F,"<$file" or die "Couldn't open file $file for reading!\n";
my @lines = <F>;
close F;
# open the file for writing
open F,">$file" or die "Couldn't open file $file for writing!\n";
foreach my $line (@lines) {
$line =~ s/<!--mydir-->/$mydir/g;
print F $line;
};
close F;Something like this should work:
[Note that with the RE above, mydir can't contain any hyphens (-).]
If you meant that the value between <!-- and --> contains the variable to use (instead of $mydir), try this:
Code: Select all
$mydir = "/mypath/folder";
$file = "The directory is <!--mydir-->";
$file =~ s/<!--ї^\-]+-->/$mydir/e;
print $file;If you meant that the value between <!-- and --> contains the variable to use (instead of $mydir), try this:
Code: Select all
$file =~ s/<!--(ї^\-]+)-->/$$1/e;