# Move files into new sub-folders based on their last modified date. # A file modified in Jun 2011 goes into $indir\_2011\6\ # A file modified in Mar 1998 goes into $indir\_1998\3\ use File::Copy ; # Using for the move(); function use File::Path qw(mkpath) ; # Using for the mkpath(); function use Warnings ; # Cause we should $indir = "C:\\Archive\\Program1\\Backup\\" ; # Script will start here looking for matching files $total = 0 ; # Set incremental file counter to see how many files get processed each run. chdir($indir) ; # Move from current working directory to user defined directory. opendir(DIR, $indir) or die $! ; # Open $indir if we can, or fail reporting an error while ($match = readdir(DIR)) { # While were in $indir with a matching file continue. if ($match =~ /\.txt|.pgp$/i) { # Match files read to .pgp or .txt ignoring others $newlocate = $outdir . $match ; # Set where we want to move the files to $movefile = $indir . $match ; # Set a matching file with its current directory # Build variables from the matching file we're working on with Stat ($dev, $ino, $mode, $nlink, $uid, $gid, $rdev, $size, $atime, $mtime, $ctime, $blksize, $blocks) = stat($movefile) ; # Build variables from the modified date of our matching file using localtime ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime($mtime) ; $mday = sprintf('%02d', $mday) ; # Not used in this script, but returns a 2 digit day $mon = sprintf('%01d', ++$mon) ; # Returns a 1 digit month until we get to 10 then use 2, not my choice. $year = 1900 + $year ; # Returns a 4 digit year $outdir = "_" . $year . "\\" . $mon . "\\" ; # Build the directory name based on date where the file is going \_2011\9\ unless (-d $outdir) { # Doesn't seem to work right, tries to create dir even if already exists mkpath($outdir, 1) ; # Create new directory for year with applicable subdir for month of matching file. } move($movefile, $newlocate) ; # Move matching file from its current location to its new date specific home. print "Moved " . $match . " to " . $outdir . "\n"; # Moved Filename.TXT to $indir\_YYYY\M\ or $indir\_YYYY\MM\ $total++ ; # Increase file counter starting with 0 each time a file is moved. } ## end if ($match =~ /\.txt|.pgp$/i) } ## end while ($match = readdir(DIR...)) print $total. " files moved.\n" ; # Prints our total count, ie: 1030509 files moved. closedir(DIR) ; # Were done, close DIR handle on $indir exit 0 ; # Exit gracefully.