Created
June 25, 2013 16:16
-
-
Save stevenscg/5859858 to your computer and use it in GitHub Desktop.
Add Google Analytics tracking to an existing static website
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment