6

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?

  • 1
    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
5
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?

  • But I have some strange problems I described in post update. – myWallJSON Mar 28 '12 at 13:29
  • 1
    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
5
sed "/<\/head>/i\
$strToInsert" file.html

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

3
cat "$file" #(before)
1
2 </head>
3
4 </head>
5
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)
1
2 </head>
3
4 </head>
5
hello world
6 </head>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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