Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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


Here is what I have:


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

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

Whats wrong with my code?

share|improve this question
You need to protect $GASTR by putting it in double-quotes: "$GASTR" ... otherwise spaces are a problem.... Often, you can put the entire sed expression in double quotes. – Peter.O Mar 28 '12 at 13:57
up vote 5 down vote accepted
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?

share|improve this answer
But I have some strange problems I described in post update. – myWallJSON Mar 28 '12 at 13:29
it is due to ' inside your variable. I've just updated my answer and replaced all ' to ". Now it works fine. – rush Mar 28 '12 at 13:45
sed "/<\/head>/i\
$strToInsert" file.html

This will insert the new line before every </head>, but why do you have more than one?

share|improve this answer
cat "$file" #(before)
2 </head>
4 </head>
6 </head>

strToInsert="hello world"
lnum=($(sed -n '/<\/head>/=' "$file"))  # make array of line numbers
((lnum>0)) && sed -i "${lnum[$((${#lnum[@]}-1))]}i \
                      $strToInsert" "$file"

cat "$file" #(after)
2 </head>
4 </head>
hello world
6 </head>
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.