I need to replace an old google analytics code with the new universal tracking code in lots of static html files. The old code looks like this:
_uacct = "UA-XXXXXX-X"; urchinTracker();
The new code is the following:
(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-XXXXXX-X', 'xxx.com');ga('require', 'displayfeatures');ga('send', 'pageview');
I'm trying to combine bash find command and sed (CentOS 6):
find docs/ -type f -iname "*.html" -exec sed -i ':a;N;$!ba;s/_uacct = "UA-XXXXXX-X";\nurchinTracker();/(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-XXXXXX-X\', \'xxx.com\');ga(\'require\', \'displayfeatures\');ga(\'send\', \'pageview\');/g' {} \;
However, this produces the following error:
-bash: syntax error near unexpected token `('
After some research I found the brackets should be escaped as well:
find arts/ -type f -iname "bass.html" -exec sed -i ':a;N;$!ba;s/_uacct = "UA-XXXXXX-X";\nurchinTracker();/\(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-XXXXXX-X\', \'xxx.com\'\);ga\(\'require\', \'displayfeatures\'\);ga\(\'send\', \'pageview\'\);/g' {} \; > >
As you may see bash thinks something is not escaped, breaks the line and does not execute the command.
What I'm doing wrong?
If this is possible to do with another tool (let's say awk)?
awk
: unix.com/shell-programming-and-scripting/…sed
with multi-line replace