Bulk Insert Code Before </body> Tag in 100 Files
I'd like to insert
<?php include_once('google_analytics.php'); ?>
before the closing body tag of 开发者_开发技巧about 100 php files. Unfortunately the person who made the site didn't make a header or footer template.
What is the best way to do this? I've tried using grep/find for getting a list of files and piping the results through xargs to sed, but I've had no luck. I probably have the regex wrong. Can anyone help me out with this?
Also, are there any graphical tools for Apple OS X that you would recommend?
Thanks, Mike
edit
find . -print0 -name "*.php" | xargs -0 perl -i.bak -pe 's/<\/body>/<?php include_once("google_analytics.php"); ?>\n<\/body>/g'
works.
Using sed:
sed -i s/'<\/body>'/"<?php include_once('google_analytics.php'); ?>\n<\/body>"/ *.htm
The -i
option edits the file in place. If you say -iBAK
then it will create a backup of the file before editing it.
If you're interested in GUI tools, download TextMate. Put all 100 files in a folder and open that folder with TM. This will put TM in project mode, and you'll see all the files in a sidebar. Now, do Edit>Find>Find In Project
, put </body>
in the "find" field, <?php include_once('google_analytics.php'); ?></body>
in the "replace" field, hit replace and let it run.
this calls for an ed script
#!/bin/sh
for i in *.html; do
ed $i << \eof
?</body>?s/^/<?php include_once('google_analytics.php'); ?>&/
w
q
eof
done
It fires up one of the first (literally) programs ever written for Unix, Ken Thompson's ed(1)
text editor on each file and makes the necessary edit. If you want it to work on specific files rather than on every .html
in the directory, just change *.html
to "$@"
.
Reading the Wikipedia link just now, I learned something interesting. Ken Thompson made the first actual application of regular expressions, apparently they were just a mathematical expression until he wrote ed(1).
You need to supply an array with filenames in $files
to make the following solution work:
foreach ($files as $file)
{
$txt = file_get_contents($file);
$txt = str_replace('</body>', '<?php include_once(\'google_analytics.php\'); ?>'."\n".'</body>', $txt);
file_put_contents($file, $txt);
}
Dreamweaver will do a find/replace for the entire local site; I'm sure other html editors would as well.
Some IDE's like dreamweaver provide functionality to do find and replace in many files, entire folders etc. You can use one of those and do a find and replace replacing the close body tag with the code you want.
I'm not a PHP developer, but is PHP a valid XML format? It doesn't look like it but what do I know. Even if it is the success of this answer may depend more on whether the files you are working with are valid PHP. But...if it is it would be fairly simple to use an XML transform (xslt) to match the body tag, copy its content and append a new tag after the matched content.
What about a replace on
</body>
with
<?php include_once('google_analytics.php'); ?></body>
?
精彩评论