#!/usr/bin/perl -w # The Most Useful Perl Script Ever # Recursively does a find and replace on every file in a directory for any # specified string. Follows all subdirectories too. # Not original, but I could not find exactly what I wanted elsewhere. # --Johnnie Odom 3/16/08 no warnings "recursion"; # Stop complaining, Perl. # Kickoff main below here. # We take three arguments # 1) Directory to start in. # 2) Pattern to find in files. # 3) What to replace the pattern with. # # Call subroutine with the first directory. # Then go ahead and exit the program when done. if($#ARGV == 2){ #ARGV is always one less than number of arguments supplied. $curpath = $ARGV[0]; $findVar = $ARGV[1]; $replaceVar = $ARGV[2]; &changeindir($curpath); } else{ print "Incorrect number of arguments supplied.\n Argument 1: Directory to start in.\n Argument 2: Pattern to find in files.\n Argument 3: What to replace the pattern with.\n"; } # Subroutine that does all the actual work via recursion. # Take a directory name and look at all files in that subdirectory. sub changeindir { # Set the path to our input and add a trailing "/" if it does not exist. my($subpath); # Variable is private for each $subpath = $_[0]; if($subpath !~ /\/$/) { $subpath .= '/'; } # Grab all filenames in the directory passed to the routine. opendir(DIR, $subpath); my @files = readdir(DIR); closedir(DIR); # Examine each file. foreach my $file (@files) { # Reject current and higher directory entries. if (($file eq "./") || ($file eq "../") || ($file eq ".") || ($file eq "..")){ print ""; } else { $file = $subpath . $file; # Get the new proper path. # If the file is a directory, recurse into it and continue. if (-d $file){ &changeindir($file); } # If the file is a text file, perform find / replace. elsif( -T $file){ open (IN, "+<$file") or die "Could not open file $file: $!\n"; my @fileop = ; seek IN,0,0; foreach my $fileop (@fileop){ $fileop =~ s/$findVar/$replaceVar/g; print IN $fileop; } close IN; } } } } # Feel free to add print statements for logging and debugging where needed.