Saturday, October 08, 2011

Editing HTML files on the fly.

In order to track the pages on my websites with google analyitics I needed to add a block of HTML code to every page.

From there instructions:
2. Paste this code on your site
Copy the following code, then paste it onto every page you want to track immediately before the closing </head> tag

Since these are HTML pages created by hand I'd have to edit 1000's of files by hand once again.
but there is a better way.

I put a little script with sed to edit these files on the fly.

This code looks for the closing line of the head tag and inserts before it the contents of the file
 google-analytics-script

#!/bin/bash
sed -i 's/<\/head>/INSERTCODE\n<\/head>/' $1
sed -i '/INSERTCODE/ r google-analytics-script'  $1
sed -i '/INSERTCODE/ d' $1


Over here I added code to read the directory and edit every HTML file there.


#!/bin/bash
ls *.html |\
while read line
do
sed -i 's/<\/head>/INSERTCODE\n<\/head>/' $line
sed -i '/INSERTCODE/ r google-analytics-script' $line
sed -i '/INSERTCODE/ d' $line
done

Just make sure you back up your files first, and don't run this more then once.

No comments: