Search and Replace in Several Files Using PHP and Perl
October 27, 2007 § 4 Comments
Search and replace of keywords are very important in programming especially when you are working with files. I prepared and released a PHP class for this purpose. You can check it here:
http://www.phpclasses.org/browse/package/3211.html
You can use this class very easily. It has also an option to log changes/replacements that have been done in the most recent operation. I want to show you how easily we can do the search and replace stuffs using this class:
————- Code ——————
<?php
require_once('TextSearch.class.php');
$path = "/path/to/your/dir"; //setting search path
$logFile = "/path/to/your/logFile"; //setting log file
$obj = new TextSearch();
//setting extensions to search files within
$obj->setExtensions(array('html','txt'));
$obj->addExtension('php');//adding an extension to search within
$obj->setSearchKey('PHP');
//setting replacement text if you want to replace matches with that
$obj->setReplacementKey('phpResource');
$obj->startSearching($path);//starting search
$obj->showLog();//showing log
$obj->writeLogToFile($logFile); //writting result to log file
?>
------------ Code -------------------
Now that we have the PHP class to do the search and replace within files. I want to show you a Perl code snippet that I got recently while searching net and I then thought I would share that. Here it is:
——————– Code ————
#!/usr/bin/perl -w ## More scripts and tips can be found at # http://www.edlin.org/ # # Search and replace in several files # # I throw this file in my ~/bin/ # Edit the variables $search, $replace and perhaps you want to change
# the globbing then I jump to the directory with the files and just # execute msr.pl (make sure that ~/bin is in your $PATH)
use strict;
my @infiles = glob("*.html");
my $search ='dilbert';
my $replace ='wally';
# Here we go.........
foreach my $file (@infiles){
print "Processing $file\n";
open(FH,$file) || die "Cannot load $file";
my @lines=<FH>;
close(FH);
my $match=0;
foreach my $line (@lines){
if($line =~ s/$search/$replace/g){
$match=1;
}
}
if($match){
print "...Saving $file\n";
open(FS,">$file") || die "Cannot save $file";
print FS @lines;
close(FS);
}
}
——————– Code ————
I found this code in
http://www.edlin.org/perl/
.
Hope these two codes will come to your helps.
Thanks.
–
Rupom
thanks for the GREAT post! Very useful…
Programming Tutorials
I couldn’t understand some parts of this article, but it sounds interesting
please feel free to ask questions. thanks.
I am necessary wish to find