Using a shell script to install GTM on an HTML-only site

Posted by: Ed Hungerford Date Posted: April 17, 2024
Back to Case Studies

Issue

Smile Crafters is a site built almost entirely in HTML. There’s no templating going on, so every page has its own <head> and <body> element. For reference, since WordPress sites do use templating, the average GTM installation only requires editing one template. In this case, Smile Crafters has around 66 unique HTML pages, each of which need GTM.

Solution

I remembered working on a project for Hot Shot’s Secret that required replacing several links within PDF files. It turned out to be a more complicated solution than I’d hoped (requiring a Python script using the PyMuPDF library – not pretty, but it worked), but the original version of the solution involved using the “sed” command to search and replace text.

Sed, by way of explanation, is a Unix command which takes data from a file, makes edits to it, and sends the output to another file or the same file. Some things to know about sed:

  • It’s not available on Windows by default because it’s made for Unix (a different operating system).
  • However, Git Bash (a GitHub interface) is available on Windows, and emulates a Unix-like environment.
  • Therefore, we can install sed on Git Bash and use it there.

I downloaded all of the relevant HTML files from the server, and then asked TeamAI to write me a short script to the following specifications:

  1. Loop through every file I’ve downloaded.
  2. For each file, locate the <head> element.
  3. Immediately after the <head> element, use sed to insert the GTM installation code.
    1. (This is actually a search-and-replace, replacing “<head>” with “<head><script>(function…”)

The script needed a slight tweak (it used single quotes where it should have used double quotes), but otherwise worked perfectly.

After the search-and-replace was finished, I zipped up all the new HTML files, uploaded them to the server, and overwrote the existing ones. Then I ran a Screaming Frog crawl on the site to make sure the HTML was still valid.

Achievement

Quickly installed GTM on 66 different HTML pages using a shell script (rather than installing it manually on each page).

Snippet/Screenshot/Link