test/
run1.log run2.log run3.log
####
test2/
run2.log run2.log_1 run2.log_2
####
use warnings;
use strict;
use File::Basename;
use File::Copy;
use File::Find::Rule;
my $count = 1;
my $dir = 'test';
my $to_dir = 'test2';
my @files = File::Find::Rule->file()
->name('*.log')
->in($dir);
if (@files){
for (@files){
if ($_ =~ /run/i){
my_copy($_);
}
}
}
sub my_copy {
my ($base_file, $file_name) = @_;
# get just the filename
my $file = basename $base_file;
# $file_name will be empty on the initial call...
# let's set it so it's not undef
$file_name = $file if ! $file_name;
if (-e "$to_dir/$file_name"){
# strip off the _N suffix if present
$file_name =~ s/_\d+$//;
# append a new _N, then increment the count
$file_name = "${file}_$count";
$count++;
my_copy($base_file, $file_name);
}
else {
print "copying $base_file to $to_dir/$file_name\n";
copy $base_file, "$to_dir/$file_name" or die $!;
}
}
####
test2/
run1.log run2.log run2.log_1 run2.log_2 run2.log_3 run3.log
####
test2/
run1.log run1.log_1 run2.log run2.log_1 run2.log_2 run2.log_3 run2.log_4 run3.log run3.log_1