t Book t Book - 1 month ago 4
Perl Question

Perl search file recursive for string and replace

in terminal with perl how can I search all php files starting recursive from current working directory for a single or multiline pattern like:

<script>var a=''; * hamoorabi.com * </script>


Read like: find all between
<script>var a='';
and
</script>
but only if contains
hamoorabi.com
and replace it with an empty string (remove it).

As it´s javascript code there can be a bunch of unescaped characters inside the search string.

Answer

From a unix or cwygin prompt:

$ find . | grep .php | xargs ./xx1.pl

Where perl script xx1.pl is :

#!/usr/bin/perl

use strict;
use warnings;

undef $/;
for (@ARGV) {
        open(FILE,$_);
        my $content = <FILE>;
        close(FILE);
        $content =~ s/(<script>.*?)(hamoorabi.com)(.*?<\/script>)/$1$3/sg;
        open(FILE,">$_");
        print FILE $content;
        close(FILE);
}