Skip to content

Instantly share code, notes, and snippets.

Revisions

  1. @stevenscg stevenscg created this gist Jun 25, 2013.
    49 changes: 49 additions & 0 deletions google-analytics-for-static-sites.sh
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,49 @@
    #!/bin/sh
    #
    # Add a Google Analytics tag to static website files
    # @see http://adambuchanan.me/post/26345221717/updating-google-analytics-code-on-many-static-pages
    # Tested on MacOS 10.8.X
    #
    # Usage:
    # Set the GA parameters below
    # Execute the script from the top-level of the static site
    #

    GA_TRACKER_ID='UA-XXXXXXX-X'
    GA_DOMAIN='YOUR-DOMAIN.COM'

    GA_CODE=$(cat <<EOF
    <!-- Start Google Analytics Installation -->
    <script>
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','\/\/www.google-analytics.com\/analytics.js','ga');
    ga('create', '${GA_TRACKER_ID}', '${GA_DOMAIN}');
    ga('send', 'pageview');
    <\/script>
    <!-- End Google Analytics Installation -->
    EOF)
    # remove newlines
    GA_CODE=`echo ${GA_CODE} | sed -e 's/\n//g'`
    #echo ${GA_CODE}
    #exit
    # set placeholder text before the </head> tag for the code to be replaced with later.
    for match in `grep -n -r "</head>" . | grep -v .sh`; do
    file=`echo $match | cut -d":" -f1`
    line=`echo $match | cut -d":" -f2`
    sed -e "`echo $line`s/<\/head>/GOOGLE_ANALYTICS_CODE_HERE<\/head>/" -i '' "$file"
    done
    # insert the tracker code
    for match in `grep -n -r "GOOGLE_ANALYTICS_CODE_HERE" . | grep -v .sh`; do
    file=`echo $match | cut -d":" -f1`
    sed -e "s/GOOGLE_ANALYTICS_CODE_HERE/${GA_CODE}/" -i '' "$file"
    done