In most cases, you should be able to configure your CMS or blog template to insert the Google Analytics JavaScript tracking code at the end of every page in your web site.
However, you sometimes need to install the tracker code into static HTML pages which are not managed by the CMS, If you have a LOT of static HTML pages, then your fingers are in trouble.
Here’s the Bash shell script which inserts the Google Analytics tracker code into all static HTML pages. Please modify it before you run it, to meet your needs. Never forget to backup the original copy — it might work incorrectly for you:
#!/bin/sh -e # inject-google-analyticsTRACKER_ID="UA-XXXXX-X"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\"> var pageTracker = _gat._getTracker('$TRACKER_ID'); pageTracker._trackPageview(); </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; fiecho "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
very cool. I don’t even know HOW I found you, but I’m definitely trying this out.
Thanks for sharing!!!
— david · 2008-10-08 08:22 · # · Reply