2

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,

6 Answers 6

6
for file in ${fe}*; do
sed -i -e '/<!DOC/i Text to insert' "$file"
done
Sign up to request clarification or add additional context in comments.

Comments

1
#!/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" "{}" +;

Comments

0
echo "line" | cat - yourfile > /tmp/out && mv /tmp/out yourfile

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

Comments

0

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

Comments

0
for file in ${fe}*; do 
    mv $file temp
    echo "YOUR STRING" > $FILE
    cat temp >> $FILE;
done

1 Comment

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
0

Try this in perl:

perl -i.bak -p -e 's/\<\!DOCTYPE/text to replace\<\!DOCTYPE/ig' *.php

This one-liner will modify all your php files, replacing <!DOCTYPE with whatever you want + <!DOCTYPE -- you want to put it back in (-: This will also backup all the modified files with an extension of .bak, so you'll see ".php.bak" files after you run this.

The i refers to case insensitive and g is global, i.e., replace all in the file. I assume only have one, and it has the same case, so you can safely leave out the "ig" at the end.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.