If you have a bunch of static html, htm, php or other web files in subdirectories and need to add Google Analytics tracking code, here's your script!


find . -type f -iname "*.php" -or -iname "*.htm" -or -iname "*.html" | while read i; do
    echo "Processing: $i"
    sed -i 's*</BODY>\|</body>*\
<script type="text/javascript">\
  var _gaq = _gaq || [];\
  _gaq.push(["_setAccount", "UA-XXXXXXXX-X"]);\
  (function() {\
    var ga = document.createElement("script"); ga.type = "text/javascript"; ga.async = true;\
    ga.src = ("https:" == document.location.protocol ? "https://ssl" : "http://www") + "";\
    var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(ga, s);\
</script>&*' "$i"



  1. Save the script above as and put it in the root directory that you want to perform the transformations in
  2. Replace UA-XXXXXXXX-X with your Google Analytics account number
  3. Mark the script executable using
    chmod +x ./
  4. Run the script with


The find command locates (case insensitive) .php, .htm, and .html files using the -iname switch. You can modify it to recognize other file types by adding more -iname switches using the -or switch to separate them. -type f tells it to locate files only.

Output is then piped to the read command to gracefully handle file and directory names with spaces in them. Without this, we'd have to toy with the $IFS variable (see IFS variable for more on that).

The sed command then handles the replacements! The -i switch tells sed to handle the replacement in-place, meaning it will modify the file. We replaced sed's usual forward slashes with "*", so as not to conflict with the slashes in the script.

The sed script will replace </body> OR </BODY> with the tracking script and the appropriately cased closing body tag (see the &).

Leave a comment!

Comments are moderated. If your comment does not appear immediately, give it a few, it may require authorization. If you're a spam-bot, you may not leave a comment, it is strictly forbidden in the Terms of Service.

You may comment using markdown syntax (link opens in new window).

David Davis