views:

53

answers:

6

Hi guys, 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"&gt;
<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,

A: 
for file in ${fe}*; do 
    mv $file temp
    echo "YOUR STRING" > $FILE
    cat temp >> $FILE;
done
Markus Maria Miedaner
But i dont want to simply prepend some text to the file, i want to search for that text and add some text before it
Bashn00b
A: 
echo "line" | cat - yourfile > /tmp/out && mv /tmp/out yourfile

Taken from here: http://www.cyberciti.biz/faq/bash-prepend-text-lines-to-file/

Lex
Re-read the requirements.
Dennis Williamson
+6  A: 
for file in ${fe}*; do
sed -i -e '/<!DOC/i Text to insert' "$file"
done
mdom
+1  A: 
#!/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" "{}" +;
ghostdog74
A: 

Here is my proposition. It assumes that your text to insert is in a file named mytextfile.

for file in ${fe}*; do
    awk '/!DOCTYPE/{printf"%s\n",text;}{print}' text="`cat mytextfile`" $file \
        > /tmp/out
    mv /tmp/out $file
done
mouviciel
A: 
KM