开发者

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,


for file in ${fe}*; do
sed -i -e '/<!DOC/i Text to insert' "$file"
done


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


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

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


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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜