Using sed to add Google Analytics to static pages

The shell command sed is extremely powerful. Recently, I needed to add the Google Analytics JavaScript to several hundred old static html pages. I did not fancy doing that by hand and when a computer is around the boring and repetitive become an excuse to grab a shell! Here’s the script I came up with:

#!/bin/sed -f
s|<body>|<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><script type="text/javascript">try {var pageTracker = _gat._getTracker("yourcode");pageTracker._trackPageview();} catch(err) {}</script><body>|

Obviously, you would replace “yourcode” with whatever your analytics code happens to be. I used find to dig up all of the html pages and then ran this script via xargs, it would also be possible to use -exec:

find . -name "*.html" | xargs -n1

The script itself contains just one “s” or substitute command. It uses the | or pipe symbol to delimit the arguments of the command. So, the script says that when sed encounters a body tag, replace it with the Google Analytics code and a new body tag. Simple.

Related Posts:

This entry was posted in Programming and tagged , , . Bookmark the permalink.

Comments are closed.