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

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?


sed "/<\/head>/i\
$strToInsert" file.html

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


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>