Add Google Analytics Tracking Code to All Pages Automatically

If you have many HTML pages in a directory, adding Google Analytics tracking code to all of them can be a bit frustrating.

In this short tutorial, I show you how to do it with a bash script that automatically does the job.

First, copy the code from your Google Analytics console, and paste it to a file named google-analytics.

Then, write the following code to a file, say and give it the execution permission:

chmod u+x ./

# From:

# description: 
# Add Google Analytics to all HTML files in a directory. Google Analytics code should be in a file called google-analytics in the same directory as this script.

# usage:
# ./ directory

# Tested on Mac-zsh


if [ -d "$directory" ]; then
  for file in "$directory"/*.html; do
    if [[ -f "$file" ]]; then
      sed -i.bak '/<head>/r google-analytics' $file
  echo "Directory not found."

rm $directory/*.bak

Now, all you need to do is to execute the script like this:

./ <your directory>

You can find this code here on GitHub too.