sed on macOS: How to append multiple lines of text to an HTML or XML file

As a brief note about the Linux/Unix sed command, today I learned how to append multiple lines of text to an HTML (or XML) file on macOS. The short answer is that I created a sed commands file named changes.sed with these contents:

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

That sed command can be read as, “When you find the <head> tag, append the following text after it.”

Once you have that file you just need to run it with sed on the file (or files) you want to edit. I just edited a bunch of HTML files with this little shell script:

for i in `ls *html`
  echo "working on $i ..."
  sed -f changes.sed < $i > ${i}.tmp
  mv ${i}.tmp $i

I’m sure there are other/better ways to run that sed script, but hey, it works.

An important part of the solution is knowing that you have to add the backslash character at the end of each line that you want to append. If you don’t do that you’ll get an “invalid command code” error when you run the script. As it says in O’Reilly’s sed & awk book:

“To input multiple lines of text, each successive line must end with a backslash, with the exception of the very last line.”

In summary, if you ever need to append multiple lines of text with sed on macOS, I hope this little example is helpful. (The same command should work on Linux and Unix systems.)