Text file insertion via sed

I have 800+ html files that need to have a javascript added to them in the head. I can do the looping, setting filenames as variables, etc. but I cannot figure out how to insert my javascript file into the html.

My javascript is in a file named jsinsert.txt

It basically has this format: (snipped to save space)

<script type="text/javascript">
<!--
function printContent(id){
str=document.getElementById(id).innerHTML
newwin=window.open('','printwin','left=100,top=100,width=400,height=400')
newwin.document.write('<HTML>\n<HEAD>\n')
newwin.document.write('<TITLE>Print Page</TITLE>\n')
newwin.document.write('<script>\n')
newwin.document.write('function chkstate(){\n')
newwin.document.write('if(document.readyState=="complete"){\n')
newwin.document.write('window.close()\n')
newwin.document.close()
}
//-->
</script>

The above code needs to be inserted just prior to </head>
I've tried various things but I am not very fluent with sed. Here's an example:

sed '/<\/head>/i\ jsinsert.txt' <myfile.html >myfile.html.tmp
mv myfile.html.tmp myfile.html

This fails. It actually puts the words jsinsert.txt just before the </head> rather than the contents of the jsinsert.txt file. Whatever, I've tried several things but cannot get the text to insert.

As I said previously. I can do the looping through the files, extract the filenames I am working with, etc. I just cannot properly insert the contents of the jsinsert.txt file just prior to the </head> tag. Any ideas about how I accomplish that?

Try this...

awk '/<\/head>/{print x} 1' x="$(cat jsinsert.txt)" myfile.html > myfile.html.tmp

--ahamed

---------- Post updated at 08:02 AM ---------- Previous update was at 07:55 AM ----------

You have "\n" in the java script, so will not get what you want!

--ahamed

Okay, I get "awk: cmd. line:1: warning: escape sequence `\/' treated as plain `/'" when I run the command but I do get the text insertion.

You are correct though. I do not get "\n" in the insertion. :frowning: This script is for printing a specific section of a web page when clicking a print button. If I remove the \n's it still works, however, it seems to print in landscape rather than portrait. Am I correct in assuming \n indicates newline? Any way to circumvent the \n situation?

The normal way...

while read line
do
  grep -q "</head>" <<<$line && cat jsinsert.txt >> myfile.html.tmp
  echo $line >> myfile.html.tmp
done < myfile.html

if grep doesn;t support -q option, use this

echo $line | grep "</head>" >/dev/null && cat jsinsert.txt >> myfile.html.tmp

--ahamed

The "normal way" works properly for me ahamed. I appreciate your help here. I'll finish out my script and do a test run on a duplicate of the folder of html files. I shall post my results. Thank you very much.