1

I wrote the following script:

#!/bin/bash
# Add Google Analytics code to every html file in the current folder and subfolders

codice="<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-XXXXXXXX-X', 'example.net');
  ga('send', 'pageview');

</script>"

original_string=$(printf %q "$codice") # it expands the string in a shell-escaped format
string_to_search='/'
string_to_replace='\/'
result_string="${original_string//$string_to_search/$string_to_replace}" # it escapes also slashes "/"

recursive() {
  for file in *; do
    if [ -d "$file" ]; then
      (cd "$file"; recursive)
    fi
    if [[ "$file" =~ \.html?$ ]]; then
    perl -i.bak -e 'undef $/; $_=<>; s/<\/body>\n<\/html>/\n'"${result_string}"'\n<\/body>\n<\/html>/gi; print' $file
    echo $file fatto
    fi
  done
}

recursive

This is an example input file:

<html>
<head>
</head>
<body>
test page
</body>
</html>

After the script execution, the file is modified so:

<html>
<head>
</head>
<body>
test page


<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-XXXXXXXX-X', 'example.net');
  ga('send', 'pageview');

</script>'
</body>
</html>

There is something strange: why there is an extra character (single quote) after the script end tag? Thank you for any help

3 Answers 3

1

The only line i changed to make it work as intended is :

result_string="${codice//$string_to_search/$string_to_replace}" # it escapes also slashes "/"

I don't know why it fixed it, neither why you want/need a printf %q "$codice" for your uses

1

Without wanting to pass comment on the inherent dirtiness of embedding a 'perl -e' within a shell script. Your regex is:

s/<\/body>\n<\/html>/\n'"${result_string}"'\n<\/body>\n<\/html>/gi;

You may find it worth swapping the delimiting '/' to a comma, for clarity.

s,</body>\n</html>,\n'"${result_string}"'\n</body>\n</html>,gi;

Anyway, I think the core of your problem will be that you're embedding a ' within your regexp, but also using it as your delimiter for the perl -e. So actually you're passing a string literal to perl, which you're closing, then embedding ${result_string} as a shell variable, before continuing your pattern. And then quoting with a mix of single and double quotes.

I would instead strongly consider a rewrite of your bash script into pure perl, as it'll make life a lot better in the long run.

#!/usr/bin/perl

# Add Google Analytics code to every html file in the current folder and subfolders

use File::Find; 

use warnings;
use strict;

my $codice="<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-XXXXXXXX-X', 'example.net');
  ga('send', 'pageview');

</script>";

sub insert_codice
{
  my $filename = $File::Find::name;
  return unless $filename =~ m/.html?\Z/;
  { 
    my $backup = "$filename.bak";
    local $/ = undef; 
    open ( my $input_fh, "<", $filename );
    my $input_text = <$input_fh>;
    close ( $input_fh );

    open ( my $backup_fh, ">", "$filename.bak" );
    print {$backup_fh} $input_text;
    close $backup_fh;

    open ( my $output_fh, ">", $filename );
    $input_text =~ s,</body>\n</html>,$codice\n</body></html>,gi;
    print {$output_fh} $input_text;
    close $output_fh;
  }
}

find ( \&insert_codice, "." );

I think something like that will do what you want. You can find more detail on the File::Find module - which is basically a neater way of doing recursive directory traversal on perldoc: http://perldoc.perl.org/File/Find.html

3
  • I'm a beginner in Perl. Maybe the first line should be #!/usr/bin/perl (you missed the first slash), however your code doesn't run in my machine, I've got this error: no &wanted subroutine given at /usr/share/perl/5.14/File/Find.pm line 1064 Apr 12, 2014 at 16:32
  • Details on File::Find should be here: perldoc.perl.org/File/Find.html Typo on my part - should be the other way around: find(\&wanted, @directories_to_search); So: find ( \&insert_codie, "." ); (I shall edit accordingly)
    – Sobrique
    Apr 12, 2014 at 17:11
  • @Sobrique +1 for good advice. Btw, instead of next, you want return. I was also going to tighten up your code, but ended up making so many changes that creating a new post felt more appropriate.
    – Miller
    Apr 12, 2014 at 18:26
0

As Sobrique has already advised, doing this using pure perl can make your life easier. The following script also uses File::Find, but utilizes in place editing to tighten up the code.

#!/usr/bin/perl

# Add Google Analytics code to every html file in the current folder and subfolders

use warnings;
use strict;

use File::Find;

my $codice = do {local $/; <DATA>};

find(sub {
    return unless /.html?\Z/;

    local @ARGV = $_;
    local $^I = '.bak';

    my $has_analytics = 0;
    while (<>) {
        $has_analytics ||= m{\Qwww.google-analytics.com/analytics.js};
        s{(?=</body>)}{$codice}i unless $has_analytics;
        print;
    }
    #unlink "$_$^I"; # Uncomment if you want to delete the backup
}, "." );

__DATA__
<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
  ga('create', 'UA-XXXXXXXX-X', 'example.net');
  ga('send', 'pageview');
</script>

I've made some enhancements where it will avoid adding google analytics if it thinks that the html file already contains it. Additionally, if you want to delete the backups, you can uncomment the line containing unlink.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.