Using php from unix command line to process/modify files

This trick/snippet combines the flexibility of unix/linux command line tools combined with php scripting.

If you are unfamiliar with the "find" command, you are missing out on your abilities to search and perform updates to many files.

PHP can be used to do many things, this trick will teach you how to do some of those things on many files in one go, helping you automate what would normally be a very manual process.

For example, say you need to do a find replace on many files, you could use find to get a list of all the files you wanted to change ( lets say all html files anywhere in the current directory or subdirectories in that directory )

find ./ -name "*.html"

Lets combine that with a nice command, xargs, which will split up the list and send it as input to another command.

find ./ -name "*.html" | xargs <final command>

Now we will make our php to do the replace

--------------------------------------------------------------------

array_shift($argv);

foreach($argv as $fname) {
if ( ! $fname ) die('file name required');
if ( ! file_exists($fname) ) die('file '. $fname .' cannot be found');

echo 'replacing on '. $fname ."\n";
$fcontents = file_get_contents($fname);

$rep = <<<ENDTEXT
<script type="text/javascript" src="dropdown.js"></script>
</head>
ENDTEXT;

$fcontents = preg_replace('/<\/head>/si',$rep,$fcontents);

file_put_contents($fname,$fcontents);
}

--------------------------------------------------------------------

This script goes over each argument ( takes file paths ) passed in on the command line opens the file, uses a regular expression to replace some replace the ending head tag, with an additional tag and puts the ending head tag back in place.

This would be useful if you had a website that was all static files, and you needed to make a mass update to add a new javascript to the page.

It may not be the cleanest way to do this, but it definitely beats doing this manually.

Combine the script with the command line utils, and you get

find ./ -name "*.html" | xargs php yourscriptname.php

Comments

Be the first to leave a comment on this post.

Leave a comment

To leave a comment, please log in / sign up