have you ever needed to install Google Analytics all static HTML files on your website ? If you have a large website that can be a lot of work so you have a few options.
- You can have the apache webserver install it automatically on the fly http://ballade.cs.ucla.edu/~kirill/analytics.html The downside here is that this requires CPU power and can slow things down a bit if you are not using modperl
- Search and replace all instances of the body tag with your analytics tag. You could use perl or sed on the unix command line to do this. Some ideas here
- Or just use this script from http://gleamynode.net/articles/2230/
[cc lang=”bash” tab_size=”2″ lines=”60″]
#!/bin/sh -e
# inject-google-analytics
TRACKER_ID=”UA-XXXXX-X”
#BE SURE TO CHANGE THE ID ABOVE
TRACKER_CODE=”
”
cd `dirname $0`
find -name ‘*.html.new’ -delete
find -name ‘*.html’ | egrep -v — ‘-frame.html$’ | while read -r TARGET; do
if grep -qi ”
continue;
fi
if grep -qi “$TRACKER_ID” “$TARGET”; then
continue;
fi
echo “Injecting: $TARGET”
case `grep -i ” “$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
[/cc]
Usage Tips
- this will search and insert Google Analytics code for ALL .html files so if you are in the master directory with multiple websites below be careful.
- Set your filetype to unix if you are uploading this script otherwise you will get errors
- Be sure to put in your own analytics ID