Question description

This question come from when I want to insert Google Analytics code into HTML files. Let's have a look on the code.

<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src=""></script>
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());

    gtag('config', 'UA-155361814-3');

I run four sites on my Rock64 (an alternative of Raspberry Pi). Except the site which allow users to play Tetris, all of them contains a lot of pages.

You can see there's a lot of pages on my website. So, it's impossible to do this manually. So the question is how can I insert multiple lines into a batch of text files.

How can I do this?

I searched this with Google. It seems I can use the sed command to do it. Sed is a widely used command which can deal with text files conveniently.

In order to do this, I need to create a file and paste the Google Analytics code into the file. Assume I created a file named stat.txt.

After that, I use the following command to insert the code into every HTML file.

for cf in $(grep "<head>" -lr .); do sed -i '/<head>/r stat.txt' $cf; done

grep is a very useful command to search a string. The -lr option can make the grep command return the relative path of the files contain the string <head>. for loop can get the file names returned by the grep command. I added Google Analytics code to every HTML file of my websites.

If you just want to insert multiple lines into one file. For example, the index.html. You can use the following command.

sed -i '/<head>/r stat.txt' index.html

That's all, thanks!

Last modified: February 14, 2020



Leave a Reply