How to insert a line into text document right before line containing some text in bash

sedtext processing

I have a variable say $strToInsert and I have a file file.html. I wonder how to find the last appearance of </head> and insert a new line before the line with it and fill it with $strToInsert contents?

Here is what I have:

GACODE="UA-00000000-1"

if [ "$2" = "" ]
then
    echo "Usage: $0 <url to extract doxygen generated docs into> <GA tracker code if needed>"
    echo "Using default"
else
    GACODE = $2
fi

GASTR="<script>var _gaq = _gaq || [];_gaq.push([\'_setAccount\', \'$GACODE\']);_gaq.push([\'_trackPageview\']);(function() {var ga = document.createElement('script'); ga.type = 'text/javascript\'; ga.async = true;ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);})();</script>"

but when I try:

sed -i 's#</head>#'$GASTR'\n</head>#' header.html

I get:

sed: -e expression #1, char 21: unterminated `s' command

What's wrong with my code?

Best Answer

sed -i "s#</head>#$strToInsert\n</head>#" file.html

but I'm not sure is "last appearence" means you can have several </head> in your file?

Related Question