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