#!/usr/bin/perl use Getopt::Std; use Cwd; getopt('sd'); $dirdelimiter = '/'; $dest = $opt_d ? $opt_d : Cwd::cwd(); $src = $opt_s ? $opt_s : Cwd::cwd(); if(substr($src,-1) ne $dirdelimiter) { $src .= $dirdelimiter; } if(substr($dest,-1) ne $dirdelimiter) { $dest .= $dirdelimiter; } if ($dest eq $src) { print "\n Move files from source directory to destination directory," ."\n rename them if file with same name already exists in destination directory." ."\n Usage: $0 [-s source_directory/] [-d destination_directory/]" ."\n If -s(ource) or -d(estination) is omitted, current directory is expected to be default for them." ."\n Problem right now is, that -s(ource) and -d(estination) are the same:\n " .$src."\n\n"; exit; } %files = qw(); opendir (DIR, $dest) or die $!; while ($file = readdir(DIR)) { if($file =~/[^.]/) { $files{$file} = 0; } } closedir(DIR); opendir (DIR, $src) or die $!; while ($file = readdir(DIR)) { if($file =~/^[.]+$/) { next; } $test = $file; while(exists $files{$test}) { %c = get_props($test); $files{$test} = %c; $c{no}++; $test = $c{body}.$c{no}.$c{ext}; } $files{$test} = 1; $command = "mv ".$src.$file." ".$dest.$test; print "$command\n"; system($command); } closedir(DIR); #use Data::Dumper; print Dumper(%files); sub get_props { $x = $_[0]; %y = qw(); @xt = split(/\./,$x); if(scalar(@xt) < 2) { $y{ext} = ''; } else { $y{ext} = '.'.pop(@xt); } $withoutext = join('.',@xt); @withoutexta = split(/_/,$withoutext); if(scalar(@withoutexta) < 2 || @withoutexta[$#withoutexta] =~/[^\d]/) { $y{no} = 0; $y{body} = $withoutext.'_'; } else { $y{no} = 0 + pop(@withoutexta); $y{body} = join('_',@withoutexta).'_'; } return %y; }