Archive

Archive for August, 2008

Using vi to replace a string in multiple files

August 9th, 2008

Sometime you may want to replace occurences of a string across multiple files.

There is an easy way to do so with the help of the vi editor.

This example will illustrate the power of vi:

Suppose you have 100 .html files, and you want to replace the occurence of the string ‘2007′ with ‘2008′.

As such, execute the following at your prompt:

vi *.html

This will open all the files ending with ‘.html’ in your current working directory. Then issue the following command:

:argdo %s/2007/2008/g | wq

That’s it! the above command will loop over each file, replacing (%) the word 2007 with the word 2008 globally (g) then it will save each file (w) and exit from it (q).

Note that the string to find and the string to use for replacement can be replaced with regular expressions. For instance, a caret (^) refers to the start of a line, the dollar sign ($) refers to its end, etc. So if we were to replace any line starting with ’sample’ and ending with ‘test’, one could use:

:argdo %s/^sample.*test$/g | wc

where .* matches anything in between the two string.

Note too that you may do the find and replace action without respect to the case (i.e. a search for ‘word’ will match ‘WoRd’). For that matter, simply replace ‘/g’ with ‘/gi’

Linux, Tips & Tricks

Display page load time

August 4th, 2008

You may want to display the time it took to load a page.
Following is a set of simple PHP code which would help you achieve this goal.

Place the following snippet at the very top of your page.
(Ultimately, it’s advisable to have a header file and a footer file that are included on every page of your website).

<?php
$timer_start = str_replace(" ","",microtime());
?>

Then place the following code at the very end of your footer.

<?php
$timer_end = str_replace(" ","",microtime());
$timer_diff = number_format($timer_end-$timer_start,6,'.','');
if($timer_diff<0) $timer_diff = "0.00";
echo "<div id='load-time' style='font-family: verdana; font-size: 8pt; color: #444444; text-align: center'>Page load time: <b>$timer_diff</b> second</div>";
?>

Obviously, we’re assuming here that this code should be within .php files, with the current server configuration allowing for parsing of such files.

PHP, Tips & Tricks