Hi I have a html called 1.html file like this
<div class="t_l"></div>
<some>
lines
of
codes
</some>
<div class="t_r"></div>
I want to replace the content of that div to another one, which stored in the file called “banner”.
banner file is
<other>
lines
of some
codes
</other>
So what I want to get is:
<div class="t_l"></div>
<other>
lines
of some
codes
</other>
<div class="t_r"></div>
What I come up with using perl is something like this:
# Slurp file 1.html into a single string
open(FILE,"1.html") or die "Can't open file: $!";
undef $/;
my $file = <FILE>;
open(BANNER,"banner") or die "Can't open file: $!";
undef $/;
my $banner = <BANNER>;
close BANNER;
# Set strings to find and insert
my $first_line = '<div class="t_l"></div>';
my $second_line = '<div class="t_r"></div>';
$file =~ s/$first_line\n.+?\n$second_line#s/$first_line\n$banner\n$second_line/;
close FILE;
# Write output to output.txt
open(OUTPUT,">1new.html") or die "Can't open file: $!";
print OUTPUT $file;
close OUTPUT;
The above code cannot work. Any suggestions?
You’re almost there.
The normal regex behavior of
.is to match any character except a newline..+?in your regex doesn’t work for you because there are more newline characters between$first_lineand$second_line.Using the
/smodifier tells Perl to let.match newline characters, too.(You also have an extraneous “
#s” in your expression)So a working substitution is: