Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

Update:

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

Whats wrong with my code?

share|improve this question
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
add comment

3 Answers

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
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
add comment
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
add comment
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>
share|improve this answer
add comment

Your Answer

 
discard

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.