Inserting Google Analytics Tracking Code using Shell Script

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:

# inject-google-analytics
TRACKER_CODE="<script type=\"text/javascript\">
var gaJsHost = ((\"https:\" == document.location.protocol) ? \"https://ssl.\" : \"http://www.\");
document.write(unescape(\"%3Cscript src='\" + gaJsHost + \"' type='text/javascript'%3E%3C/script%3E\"));
<script type=\"text/javascript\">
try {
var pageTracker = _gat._getTracker('$TRACKER_ID');
} catch(err) {}</script>"

find . -name '*' -delete
find . '(' -name '*.html' -and -not -name '*-frame.html' ')' | while read -r TARGET; do
  if grep -qiP "(<frameset|$TRACKER_ID)" "$TARGET"; then

  if grep -qiF '</body>' "$TARGET"; then
    perl -pi -e "s/(<\/body>)/\n${TRACKER_CODE////\/}\n$1/i" < "$TARGET" > "$"
    { cat "$TARGET"; echo; echo "$TRACKER_CODE"; echo; } > "$"
  if ! grep -qF "$TRACKER_ID" "$"; then
    echo "Failed to inject analytics script: $TARGET"
    cat "$"
    rm -f "$"
    exit 1
  mv -f "$" "$TARGET"

1 Comment Inserting Google Analytics Tracking Code using Shell Script

Comments are closed.