Reply to comment

Move Files into a Directory Named for the Modification Date

This script is being used to move files around in a Maildir. A bunch of spam goes into the "new" directory. When this script is run, it moves the files into directories based on the mtime, into directories named for the date when the file was modified.

#! /usr/bin/perl

# move files into directories named by date
# a file modified on 2009-07-11 will be moved into a directory named "2009-07-11".

$dir = $ARGV[0];

$dir = 'new' if ! $dir;

opendir DH, $dir;

while ($fn = readdir DH)
        next if ($fn =~ /^\./);

        $filename = "$dir/$fn";
        ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks) = stat($filename);

        ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($mtime);

        $mday = sprintf('%02d',$mday);
        $mon = sprintf('%02d',++$mon);
        $year = 1900 + $year;
        $destdir = "$year-$mon-$mday";
        $destname = "$destdir/$fn";

        mkdir $destdir if (! -e $destdir);
        rename $filename, $destname;


The content of this field is kept private and will not be shown publicly.
  • Lines and paragraphs break automatically.

More information about formatting options

3 + 8 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.