递归修改文件中指定字符串


#
/bin/perl -w
use 5.010 ;

if (2 != $#ARGV) {
&Usage ;
}

my ($path, $str_to_be_replaced, $with_what) = ($ARGV[0], $ARGV[1], $ARGV[2]) ;
my ($fCount, $lCount) = &Change_Recursively($path, $str_to_be_replaced, $with_what) ;
print "Total $fCount files changed"."\n" ;
print "Total $lCount lines changed"."\n" ;


#--------------------------------------------------------------------------------------#
# Show to user how to use this program

sub Usage
{
die "Usage: \'path\' \'str_to_be_replaced\' \'with_what\'"."\n" ;
}


# @_[0]: path
# @_[1]: str_to_be_replaced
# @_[2]: with_what

sub Change_Recursively
{
my ($path, $str_to_be_replaced, $with_what) = ($_[0], $_[1], $_[2]) ;
my $fileCount = 0 ;
my $lineCount = 0 ;
opendir DH, $path
or
warn "warning: Directory \'$path\' not found" ;
my @files = readdir DH ;
close DH ;

foreach (@files) {
my $name = $path."\\".$_ ;

if (-f -e $name)
{
my $lc = &Change_Single($name, $str_to_be_replaced, $with_what) ;
$lineCount = $lineCount + $lc ;
if (0 != $lc) {
$fileCount++ ;
}
}
elsif (-d -e $name && !m/\.|\.\./)
{
my ($fc, $lc) = &Change_Recursively($name, $str_to_be_replaced, $with_what) ;
$fileCount = $fileCount + $fc ;
$lineCount = $lineCount + $lc ;
}
}

(
$fileCount, $lineCount) ;
}


# @_[0]: filename
# @_[1]: str_to_be_replaced
# @_[2]: with_what

sub Change_Single
{
my ($filename, $str_to_be_replaced, $with_what) = ($_[0], $_[1], $_[2]) ;
my $lineCount = 0 ;

# Read data to memory
open F, "<", $filename
or
warn "$filename not found" ;
my @content = <F> ;
close F ;

foreach (@content) {
if (s/$str_to_be_replaced/$with_what/g) {
$lineCount++ ;
}
}

# Write back to file
open F, ">", $filename
or
warn "warning: File \'$filename\' not writable" ;
print F @content ;
close F ;
$lineCount ;
}

  

posted @ 2011-07-26 22:54  walfud  阅读(348)  评论(0编辑  收藏  举报