You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
104 lines
1.8 KiB
104 lines
1.8 KiB
#!/usr/bin/perl
|
|
|
|
my $help = <<'END_HELP';
|
|
Sampling tool 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.
|
|
Does NOT rename anything unless DOIT!
|
|
|
|
Special Variables are:
|
|
%NR% - the index number for the file with the current sorting
|
|
|
|
no captures support in regex :(
|
|
END_HELP
|
|
|
|
|
|
use strict;
|
|
use warnings;
|
|
|
|
use Data::Dumper qw(Dumper);
|
|
use POSIX qw(strftime);
|
|
use Cwd;
|
|
use File::stat;
|
|
|
|
my $dir = "-?";
|
|
$dir = $ARGV[0];
|
|
my $regexSearch = $ARGV[1];
|
|
my $regexReplace = $ARGV[2];
|
|
my $reallyDoIt = $ARGV[3];
|
|
|
|
if ($dir eq "-?") {
|
|
usage();
|
|
}
|
|
|
|
if(!$dir) {
|
|
print "Error: Need a directory.\n";
|
|
die "\n";
|
|
}
|
|
if(!$regexSearch) {
|
|
print "Error: Need a search regex.\n";
|
|
die "\n";
|
|
}
|
|
if(!$regexReplace) {
|
|
print "Error: Need a replace regex.\n\n";
|
|
die "\n";
|
|
}
|
|
|
|
chdir($dir) || die "FATAL: cant chdir";
|
|
|
|
print getcwd()."\n";
|
|
|
|
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 = "";
|
|
|
|
my $fname_new = "";
|
|
my $counter = 1;
|
|
my $regexReplaceNew = "";
|
|
my $counterFmt;
|
|
for (@sorted_files) {
|
|
$fname = $_;
|
|
$fstat = stat($_);
|
|
$mtime = strftime('%Y/%m/%d %H:%M:%S',localtime($fstat->mtime));
|
|
|
|
$regexReplaceNew = $regexReplace;
|
|
$counterFmt = sprintf("%03s",$counter);
|
|
$regexReplaceNew =~ s/%NR%/$counterFmt/g;
|
|
|
|
$fname_new = $fname;
|
|
$fname_new =~ s/$regexSearch/$regexReplaceNew/;
|
|
# $fname_new =~ s/(.*?)\s1-/%NR%_$1/;
|
|
|
|
printf "%-40s%-40s%-20s\n",$fname_new,$fname,$mtime;
|
|
|
|
if($reallyDoIt) {
|
|
rename($fname,$fname_new);
|
|
}
|
|
|
|
$counter++;
|
|
}
|
|
|
|
|
|
|
|
sub usage {
|
|
print $help;
|
|
die "\n";
|
|
}
|
|
|