Add Google Analytics snippet to multiple .html files recursively with a Groovy Script

Scenario: You have a static HTML website. With many .html files. You want to add the Google Analytics tracking snippet to every file. It is easy to create a Groovy script do it. Let me show you.

Create a build.gradle file which uses the Groovy Gradle plugin and the Gradle Application Plugin.

apply plugin: 'groovy'
apply plugin: 'application'

mainClassName = "demo.Main"

repositories {

dependencies {
    compile 'org.codehaus.groovy:groovy-all:2.4.13'
$ mkdir -p src/main/groovy/demo
$ touch src/main/groovy/demo/Main.groovy

Create a file src/main/groovy/demo/Main.groovy

package demo
import static

class Main {
    public static void main(def args) {
        final String path ='/Users/sdelamo/website'
        if ( !new File(path).exists() ) {
            println "${path} does not exist"
        final String code = 'UA-XXXXX-2'
        final String codePreffix = 'UA-'
        final String analyticsSnippet = """<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="${code}"></script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', '${code}');

        final String fileSuffix = '.html'
        addGoogleAnalyticsSnippet(path, fileSuffix, codePreffix, analyticsSnippet)

    static addGoogleAnalyticsSnippet(String path, String fileSuffix, String codePreffix, String analyticsSnippet) {
        new File(path).eachFileRecurse(FILES) {
            if ( {
                if (!(it.text.contains(codePreffix))) {
                    println "adding analytics snippet to ${}"
                    String text = it.text
                    it.text = text.replaceAll('<head>', "<head>\n${analyticsSnippet}".toString())
                } else {
                    println "${} already contains Google analytics snippet."


Add gradlew wrapper

$ gradle wrapper

Run your script; Gradle run task is provided by the Gradle Application plugin

$ ./gradlew run

Tags: #groovy