if( @ARGV < 2 || (@ARGV < 3 && $ARGV[@ARGV-1] eq "test")){
print "Usage: DAMit2 dam.txt file [file] ... [test]\n";
print "The \"test\" option will output the log, but not apply changes.\n";
print "Examples:\n";
print "DAM all files in current directory:\n";
print " DAMit2 dam.txt *.*`\n";
print "DAM all .h files in current directory (recursive), but do not apply changes:\n";
print " DAMit2 dam.txt `find -name \\*.h` test\n";
print "DAM all .h, .c, and .cpp files in current directory (recursive):\n";
print " DAMit2 dam.txt `find -name \\*.cpp` `find -name \\*.\\[hc\\]`\n";
exit;
}
$damfile = shift(@ARGV);
if($ARGV[@ARGV-1] eq "test"){
$TESTING = 1;
pop(@ARGV);
}else{
$TESTING = 0;
}
open(DAM, $damfile) || die( "Unable to open $damfile : $!\n" );
%hash = ();
while( <DAM> ){
next if /^#/;
chop;
($old, $new) = split /\s+==>\s+/;
$hash{ $old } = $new if $old && $new;
}
close DAM;
foreach $arg (@ARGV){
&CMreplaceALL();
}
print "DAM'ed ".scalar(@ARGV)." files.\n";
sub CMreplaceALL{
open FILE, "+<$arg" or die "Cannot open $arg: $!\n";
flock FILE, 2;
@data = <FILE>;
print "For file: $arg\n";
$total = 0;
$line = 1;
foreach (@data){
$before = $_;
$replace = 0;
while( ($old, $new) = each %hash ){
eval '$count = ($_ =~ '."s/\\b$old\\b/$new/g)";
$replace += $count;
}
$total += $replace;
print "$line: -$before$line: +$_" if $replace != 0;
$line++;
}
if( $total == 0 ){
print "No replacements made in $arg\n\n";
}else{
if( !$TESTING ){
seek FILE, 0, 0;
truncate FILE, 0;
print FILE @data;
}
print "Made $total total replacements in $arg\n\n";
}
close FILE;
}