Posted on April 29th, 2009 by msamir
Category: Linux, bash, Tags: google-analytics, web
In some cases you create static html/htm file away from whatever CMS you may use (Wordpress – Joomla – Drupal) so your google analytic code “javascript” need to be inject manually.
In case like this and when you have many html/htm files you can use this script to automatically insert google code to them
Pleas take care from the following point:
1- Change TRACKER_ID to be Your
2- Edit the script to meet your need for example if your file have extension htm/html .. etc
3- Backup the original html/htm files
Download The Script
#!/bin/sh -e
# inject-google-analytics
TRACKER_ID=”UA-7402929-1”
TRACKER_CODE=”<script type=”text/javascript”>
var gaJsHost = ((“https:” == document.location.protocol) ? “https://ssl.” : “http://www.”);
document.write(unescape(“%3Cscript src=’” + gaJsHost + “google-analytics.com/ga.js’ type=’text/javascript’%3E%3C/script%3E”));
</script>
<script type=”text/javascript”>
try {
var pageTracker = _gat._getTracker(‘$TRACKER_ID’);
pageTracker._trackPageview();
} catch(err) {}</script>”
cd `dirname $0`
find -name ‘*.html.new’ -delete
find -name ‘*.html’ | egrep -v — ‘-frame.html$’ | while read -r TARGET; do
if grep -qi “<frameset” “$TARGET”; then
continue;
fi
if grep -qi “$TRACKER_ID” “$TARGET”; then
continue;
fi
echo “Injecting: $TARGET”
case `grep -i ‘</body>’ “$TARGET” | wc -l` in
1)
cat “$TARGET” | sed “s:\(<\/BODY>\|<\/body>\):`echo $TRACKER_CODE | sed ’s:;:\\;:g’ | sed ’s/:/\\:/g’`\1:gi” > “$TARGET.new”
mv -f “$TARGET.new” “$TARGET”
;;
*)
{
cat “$TARGET”
echo “$TRACKER_CODE”
} > “$TARGET.new”
mv -f “$TARGET.new” “$TARGET”
;;
esac
done |