编辑HTML文件并替换字符串。怎么样?

时间:2014-01-24 07:08:07

标签: html perl

我有一个名为“aud.html”的HTML文件。我想编辑此文件以搜索$ stream_name变量中存在的特定字符串,并在html文件中替换相同的字符串。下面是我的代码,但它不起作用。有什么问题吗?

 $RESULTS_FILE = "/aud.html";
open OUT, ">>", $RESULTS_FILE or die "Could not open results file:$!";
$j=0; 
while($ln=<OUT>)
        {
                chomp($ln);
                print "Result file value is:$ln\n";
                if( $ln =~ m/$stream_name[$j]/ )
                {
                        print "Matched streamname with logcat file:$ln\n";
                        print "s/$ln/$stream_name NOT-RUN/g";
                        print OUT "s/$ln/$stream_name[$j]-NOTRUN/g";
                        $j++;
                }
        }

2 个答案:

答案 0 :(得分:0)

您可以读取文件,替换文本并将其写入新的html文件:

$RESULTS_FILE = "aud.html";
open OUT, "<", $RESULTS_FILE or die "Could not open results file:$!";

my @a;   
while ($ln=<OUT>) {
    chomp($ln);
    for my $str (@stream_name) {
        if ( $ln =~ m/$str/ ) {
            $ln =~ s/($str)/$1 NOT-RUN/g;
        }
    }
    push @a, $ln;
}

open F, ">out.html" || die "$!";
for my $e (@a) {
    print F "$e\n";
}
close F;

答案 1 :(得分:0)

试试此代码

$RESULTS_FILE = "aud.html";
    open(FILE, "<$RESULTS_FILE") || die "File not found";
    my @lines = <FILE>;
    close(FILE);

    my @newlines;
    foreach(@lines) {
       $_ =~ s/find/replace/g;
       push(@newlines,$_);
    }

    open(FILE, ">$RESULTS_FILE") || die "File not found";
    print FILE @newlines;
    close(FILE);