perl script to replace the text in the original file

Hi Folks,

I have an html file which contains the below line in the body tagI am trying the replace hello with Hello Giridhar programatically.

<body>
<P><STRONG><FONT face="comic sans ms,cursive,sans-serif"><EM>Hello</EM></FONT></STRONG></P>
</body>

I have written the below code to replace the string and I am able to print it but how to replace the string(Hello Giridhar) in the html file.

Please correct the code where you think I made the mistakes.

 
my $filename = "theme1.htm";
my $old = "Hello";
my $new = "Giridhar";
$new = "$old ".$new;
open(my $fh, '<', $file_name) || die "file could not open $! \n";
while( $line = <$fh>) 
{
        if( $line =~ s/$old/$new/g ) 
        {
               print  "$line\n";
        }
}
close($fh);
 

Thanks in advance...

my $filename = "theme1.htm";
my $old = "Hello";
my $new = "Giridhar";
$new = "$old ".$new;

$^I = ".orig";
$ARGV[0] = $filename;

while( <> ) 
{
    s/$old/$new/;
    print;
}
1 Like

lot of thanks bajaje...

For my understanding, Could you please explain the below lines of code..

$^I = ".orig";
$ARGV[0] = $filename;

Regards,
Giridhar

$^I enables in-file editing. ".orig" will be the extension added to original file and kept in the same directory. So after in-file editing "abc.html" would be retained as "abc.html.orig" in the same directory.

The diamond operator (<>) in while loop iterates over the content in @ARGV. $filename is the first element of array @ARGV.

1 Like