#track pad by Dale Swanson October 15th 2009 #Go through folders recursivly and find filenames with " - 1 - " and renames to " - 01 - ". Used for renaming mp3s so the tracks are always two digits. #!/usr/bin/perl use strict; use warnings; use Cwd; my @allfiles; #stores all the files in the directory my $file; #used to access each file in the allfiles array my @dirs; #array of all the directories my $dirname; #used to store the directory name of a directory my $dircount; #count of all the directories, not currently used my $dir; #the name of the directory being worked with my $startdir; #name of the directory the program is ran from my $debug = 0; #debug mode, set to 1 to get lot's of output my $front; #front part of the filename my $mid; #mid part of filename my $end; #end part of filename my $newname; #the new filename with 0 padded digit system("CLS") if ($debug); (print "\n") if ($debug); $dir = cwd(); #starting directory $startdir = $dir . "/"; #add the slash since it's not there by default sub listfiles {# goes through all the files in the current directory, finds the other directories, and the files matching filetype (print "\ndir - $dir") if ($debug); opendir THISDIR, $dir or die "Can't open directory: $!"; @allfiles = grep !/^\.\.?$/, readdir THISDIR; #gets all the files in this directory, strips . and .. closedir THISDIR; (print "\nALL FILES:\n@allfiles\n") if ($debug); foreach $file (@allfiles) {# go through each file, check to see if it's a directory or the filetype we want (print "\nTest File - $file") if ($debug); if (-d $dir . "/" . $file ) {# if it's a directory (print "\nList DIR - $file") if ($debug); $dirs[$dircount] = $dir . "/" . $file; #adds the directory's name to the array of directories $dircount++; } if ($file =~ /\s-\s\d\s-\s/) {# a file with the pattern " - 1 - " was found (print "\nList File - $file") if ($debug); $front = $`; #front part of the filename, before the " - 1 - " $mid = $&; #the " - 1 - " part $end = $'; #end of filename, after " - 1 - " $mid =~ m/(\d)/; #extract just digit $mid = $1; #extract just digit $mid = sprintf("%02d",$mid); #pad digit with a zero $newname = "$front - $mid - $end"; #combine into new filename (print "\nNew Name - $newname") if ($debug); $newname = $dir . "/" . $newname; #include the directory in the filename $file = $dir . "/" . $file; #include the directory in the filename (print "\nNew Name - $newname") if ($debug); rename ($file, $newname); #rename the file with the new name } } (print "\n***\nAll Directories:\n@dirs\n") if ($debug); } &listfiles; #run the sub for the first time foreach $dirname (@dirs) {# go through all the directories, and run the main sub, to find more files $dir = $dirname; (print "\ndirname - $dirname, dir - $dir") if ($debug); &listfiles; }