Search and replace text recursively
#! /usr/local/bin/perl -w
# srep.pl replaces text in files matching the specified pattern.
# It recurses through subdirectories. The first argument is the
# start directory, the second a pattern for filenames, the third
# is the text to be replaced and the fourth the replacement string.
# If you want to backup the original file(s) call srep.pl with a
# fifth argument, that evaluates to true in a boolean context,
# e.g. backup. Replacements occur globally, are case-insensitive,
# and '.' also matches '\n'.
#
# Copyright 2003, Ramiro Gómez.
#
# This program is free software; you can redistribute it and/or
# modify it under the same terms as Perl itself.
use strict;
use File::Find; # included with Perl since Perl 5.00307
unless (scalar(@ARGV) >= 4) {
die "Usage: $0 directory filename searchstring replacement [backup]
e.g.: $0 '.' 'html?\$' 'h1>' 'h2>' backup\n";
}
# Configuration variables
my $dir = shift;
my $name = shift;
my $regex = shift;
my $replace = shift;
my $backup = shift;
# array of changed files
my @changed;
# Recurse dirctories
File::Find::find({wanted => \&wanted}, $dir);
# Print report
print map { "$_ changed\n" } @changed;
print scalar(@changed) . " file(s) changed\n";
exit;
sub wanted {
if (/$name/i) {
return unless -f $_; # only change files
open(IN ,$_) or die $!;
my $content;
read(IN, $content, -s $_);
close(IN) or die $!;
if ($content =~ s/$regex/$replace/gis) {
push @changed, $File::Find::name;
if ($backup) {
rename $_, $_ . '.bak' or die "Can't rename $_: $!";
}
}
open(OUT, ">$_") or die "Can't open $_: $!";
print OUT $content;
close(OUT) or die "Can't close $_: $!";
}
}
Post new comment