Global Search and Replace

Mark Ellis mark.ellis at rpl.richmond.bc.ca
Fri Nov 7 16:30:46 EST 1997


Peter Gorman said:

>Aw, why focus on the negative? Let's hear what *works*. I'd like to be able
>to recommend something to my poor benighted Windows colleagues! <duck>
>

There's Windows program called, oddly enough, "Search and Replace" which
can be found at www.shareware.com.

You can also use Perl, which might be more flexible in some circumstances.
(see below)

And remember:

(choose best answer for this context)

[ ] Make a backup.
[ ] Use a condom.
[ ] Say "please".


# replace.pl
# 02-04-96 Mark Ellis <mark.ellis at rpl.richmond.bc.ca>
# Searches and replaces text in .html files in a specified directory and
all sub-directories.
# Set the substitution using following two variables.
# If no directory arguement is given, the program will start in the current
directory.
#########################################################################
$to_replace = "\xd0";  # evil dash
$replace_with = "-"; # regular dash
#########################################################################
$dir = $ARGV[0];
if ($dir eq "") { $dir = "."; }
&DoDir($dir);

sub DoDir  {

chdir(@_[0]) || die "Can't change to @_[0] directory\n";
opendir(DIR, ".") || die "Can't open @_[0]\n";
local(@filenames) = grep(!/^\.\.?$/, readdir(DIR)); # grep to avoid "." and ".."
closedir(DIR);

       foreach $filename (@filenames)  {

               if ($filename =~ /\.html$/)  {
                       # print "HTML file: ", "$filename\n"; #debug
                       &Replace($filename);
               }
               if (-d $filename)  {
                       # print "Directory: ", "$filename\n";  #debug
                       &DoDir($filename);
               }
       }
chdir("..");
}

sub Replace {

$input_file = @_[0];
$output_file = "changed.tmp";

open( INPUTFILE, $input_file)  || die "Can't open $input_file $!\n";
open( OUTPUTFILE, ">>$output_file") || die "Can't open $output_file $!\n";

       while ( <INPUTFILE> ) {
               s/$to_replace/$replace_with/g;  # Perform global substitution.
               print OUTPUTFILE;
       }

close(OUTPUTFILE);
close(INPUTFILE);

# Delete input file and replace it with the output file
#
unlink $input_file || die "Can't delete input file: $input_file\n";
rename( $output_file, $input_file ) || die "Can't rename $output_file to
$input_file\n";
}


----------------------------------------------------------------------------
Mark Ellis
Network Support Analyst                 Phone: (604) 231-6410
Richmond Public Library                 Email: mark.ellis at rpl.richmond.bc.ca
Richmond, British Columbia
----------------------------------------------------------------------------




More information about the Web4lib mailing list