Search code examples
bashshellediting

Bash Scripting: I want to open a set of .php files, and add line before html tag


I have a set of .php files in a folder, I want to add text just before these lines:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" >

What i want is to insert just before these lines in the html file. So just want to prepend that file before each docType declaration. However the DOCTYPE declaration is never on line 1, as there is loads of php lines before.

I have this current script (where FE is the folder containing all the scripts i want to edit):

for file in ${fe}*; do
      echo "$file"
done

Thanks,


Solution

  • #!/bin/bash
    shopt -s nullglob
    text2add="my text to add"
    for file in *.php
    do
      if [ -f "$file" ];then
         sed -i.bak "/<\!DOCTYPE/ i $text2add" $file
      fi
    done
    

    Or just simply

    text2add="my text to add"
    sed -i.bak "/<\!DOCTYPE/ i $text2add" *.php
    

    If you want to do it recursively

    find . -iname "*.php" -exec  sed -i.bak "/<\!DOCTYPE/ i $text" "{}" +;