Need to add code to hundreds of .html files

Need assistance to add code to hundreds of .html

Code will look like below and needs to be added below <html> tag:


<script>

Some .js code here

</script>

This will be used in Fedora release 7 (Moonshine).

I will appreciate any type of help and/or orientation.

Thank you!

try

for file in $(ls -ltr *.html | awk '{ print $9 }')
do 
 for filedata in $(cat $file) 
 do
  if [ $filedata == "<html>" ]; then
   echo "<script>" >> $file
   echo "Some .js code here" >> $file
   echo "</script>" >> $file
  fi 
 done
done

Hi Makarand,
Why use:

for file in $(ls -ltr *.html | awk '{ print $9 }')

instead of:

for file in *.html

The second form will not fail due to ARG_MAX limits nor filenames containing whitespace characters; doesn't need to start up a subshell, doesn't need to invoke ls or awk ; and will run faster.

All expansions of $file and $filedata also need to be quoted.

It also seems strange that this code replaces everything in every input file with one copy of the text that was supposed to be added after every occurrence of the word <html> in the corresponding input file instead of adding that text to the existing file in the specified spot(s).

Hi Ferocci,
Is the text to be added contained in a file, or is it just a string in your script?

I don't have time to give a complete proposal tonight, but if I was doing this I'd probably use ed -s "$file" in a loop instead of reading the files line by line in the shell (and I certainly wouldn't use echo to copy the results back to the files being processed.

Do you need more help with this?

1 Like

Below code will create new files (*.out) with required changes

for i in *.html
do
awk '/^[ \t]*<[Hh][Tt][Mm][Ll][ >]/ {print; getline
 print "<script>"
 print "Some .js code here"
 print "</script>"}1' "${i}" > "${i}.out"
done

If you want to make the changes to the file

for i in *.html
do
awk '/^[ \t]*<[Hh][Tt][Mm][Ll][ >]/ {print; getline
 print "<script>"
 print "Some .js code here"
 print "</script>"}1' "${i}" > "${i}.out"
mv "${i}.out" "${i}"
done

Try also

sed -r '/<(html|HTML)/ r insertfile' *.html

given your script is in insertfile. This works, but is not tested against all possible html- pages. Refine/adapt if need be.