PERL script that does a search and replace on all files in folder

Here is a script I wrote a few days ago to make a mass change to one of my sites. I write PERL scripts often, but this one seems like one that I’ll be using again in the future.

Copy this PERL script to the folder you want to process. A backup will be made of all changed files.

For more regular expressions that you can use, search the regular expressions library: http://regexlib.com/

# Takes all files in folder (filter by filename), and uses regular expression to find a string to replace.
# If string exists, it makes a backup (appends .bak extension) and does replacement
@files = <*>;

# regular expressions allowed

# only change these files, $filefilter = "*" for all files
$filefilter = "\.php";  

$searchfor = "google\.com";
$replacewith = "strivingafterwind\.com";

foreach(@files){
	$filename = $_;
	if($filename =~ /\.php$/i){

		open(MYINPUTFILE, "<$filename");
		@all = <MYINPUTFILE>;
		close(MYINPUTFILE);

		$completefile = join("",@all);

		if($completefile =~ /$searchfor/s)
		{
			$backupfilename = $filename.".bak";
			rename($filename, $backupfilename) || die "Couldn't rename: $filename to $backupfilename!\n"; 

			$completefile =~ s/$searchfor/$replacewith/gs;
				# /g to replace all occurances.
				# /s for single line mode (since the file is all one string now)

			#print $completefile;
			open(MYOUTPUTFILE, ">$filename");
			print MYOUTPUTFILE $completefile;
			close(MYOUTPUTFILE);
		}
	}
}

Since I’m running this scripts in Windows, you might need to add the perl shebang (”#!/usr/bin/perl”) at the top if you plan to run this on linux.

0 Responses to “PERL script that does a search and replace on all files in folder”


  1. No Comments

Leave a Reply