Recursively Add Google Analytics Tracking Code Using find and sed
If you have a bunch of static html, htm, php or other web files in subdirectories and need to add Google Analytics tracking code, here's your script!
ga.sh
#!/bin/bash
# ga.sh
find . -type f -iname "*.php" -or -iname "*.htm" -or -iname "*.html" | while read i; do
echo "Processing: $i"
sed -i 's*</BODY>\|</body>*\
<script type="text/javascript">\
var _gaq = _gaq || [];\
_gaq.push(["_setAccount", "UA-XXXXXXXX-X"]);\
_gaq.push(["_trackPageview"]);\
\
(function() {\
var ga = document.createElement("script"); ga.type = "text/javascript"; ga.async = true;\
ga.src = ("https:" == document.location.protocol ? "https://ssl" : "http://www") + ".google-analytics.com/ga.js";\
var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(ga, s);\
})();\
</script>&*' "$i"
done
Instructions
- Save the script above as ga.sh and put it in the root directory that you want to perform the transformations in
- Replace UA-XXXXXXXX-X with your Google Analytics account number
- Mark the script executable using
chmod +x ./ga.sh
- Run the script with
./ga.sh
Explanation
The find command locates (case insensitive) .php, .htm, and .html files using the -iname switch. You can modify it to recognize other file types by adding more -iname switches using the -or switch to separate them. -type f tells it to locate files only.
Output is then piped to the read command to gracefully handle file and directory names with spaces in them. Without this, we'd have to toy with the $IFS variable (see IFS variable for more on that).
The sed command then handles the replacements! The -i switch tells sed to handle the replacement in-place, meaning it will modify the file. We replaced sed's usual forward slashes with "*", so as not to conflict with the slashes in the script.
The sed script will replace </body> OR </BODY> with the tracking script and the appropriately cased closing body tag (see the &).
Leave a comment!
Comments are moderated. If your comment does not appear immediately, give it a few, it may require authorization. If you're a spam-bot, you may not leave a comment, it is strictly forbidden in the Terms of Service.