2

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?

2
  • 2
    You should use one of the perl HTML parser modules, like HTML::TokeParser, for example. Commented Sep 6, 2012 at 21:50
  • You really don't want to parse HTML with regular expressions. That way lies madness :-/ Commented Sep 7, 2012 at 9:42

2 Answers 2

2

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_line and $second_line.

Using the /s modifier tells Perl to let . match newline characters, too.

(You also have an extraneous "#s" in your expression)

So a working substitution is:

$file =~ s/$first_line\n.+?\n$second_line/$first_line\n$banner\n$second_line/s;
Sign up to request clarification or add additional context in comments.

Comments

1

Go with

$file =~ s/($first_line\n)[^\n]+(\n$second_line)/$1$banner$2/;

or

$file =~ s/(?<=$first_line\n)[^\n]+(?=\n$second_line)/$banner/;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.