#!/usr/bin/perl my $help = <<'END_HELP'; File Renamer usage: renamer.pl DIR SEARCHREGEX REPLACEREGEX [--doit] for every regular file in DIR, sorted by mtime, replaces the SEARCHREGEX with REPLACEREGEX in every filename. if the new name clashes with an already existing file, a count will be appended before the first dot. Does NOT rename anything unless --doit Special Variables are: %NR% - the index number for the file with the current sorting %MTIME% - the modification time of the file no captures support in regex :( END_HELP use strict; use warnings; use Data::Dumper; use POSIX qw(strftime); use Cwd; use File::stat; # print(Dumper(@ARGV) . "\n"); # print("size:" . int(@ARGV) . "\n"); if (int(@ARGV) < 3) { usage(); } my $dir = $ARGV[0]; my $regexSearch = $ARGV[1]; my $regexReplace = $ARGV[2]; my $reallyDoIt = $ARGV[3] || 0; if (!-d $dir) { print("$dir - no such dir" . "\n"); exit(-1); } if ($reallyDoIt eq "--doit") { $reallyDoIt = 1; } else { print("Dry run. Not renaming anything." . "\n"); } chdir($dir) || die "FATAL: cant chdir"; opendir(DIR, getcwd()); my @files = readdir(DIR); closedir(DIR); #filter out dirs my @filesNoDir; foreach (@files) { if (!-d $_) { push(@filesNoDir, $_); } } @files = @filesNoDir; my @sorted_files = sort {stat($a)->mtime <=> stat($b)->mtime} @files; my $fname = ""; my $fstat = ""; my $mtime_display = ""; my $mtime_filename = ""; my $fname_new = ""; my $counter = 1; my $regexReplaceNew = ""; my $counterFmt; for (@sorted_files) { $fname = $_; $fstat = stat($_); $mtime_display = strftime('%Y/%m/%d %H:%M:%S', localtime($fstat->mtime)); $mtime_filename = strftime('%y%m%d_%H%M%S', localtime($fstat->mtime)); $regexReplaceNew = $regexReplace; $counterFmt = sprintf("%03s", $counter); $regexReplaceNew =~ s/%NR%/$counterFmt/g; $regexReplaceNew =~ s/%MTIME%/$mtime_filename/g; $fname_new = $fname; $fname_new =~ s/$regexSearch/$regexReplaceNew/; # $fname_new =~ s/(.*?)\s1-/%NR%_$1/; my $fname_result = $fname_new; my $count_clash = 0; while(-e $fname_result) { my $count_clash_fmt = sprintf("%02s", $count_clash); $fname_result = $fname_new =~ s/(.*?)\./$1_$count_clash_fmt./r; $count_clash++; } printf "%-60s%-60s%-20s\n", $fname_result, $fname, $mtime_display; if ($reallyDoIt) { rename($fname, $fname_result); } $counter++; } sub usage { print $help; die "\n"; }