Moving files to subdirectories based on date in the filename

My camera produces JPG files that have date and time information in the file name. I want to  move the files to new subdirectories per year, month and day.
IMG_20150723_233831.jpg -> 2015/07/23/IMG_20150723_233831.jpg
IMG_20151001_174215.jpg -> 2015/10/01/IMG_20151001_174215.jpg

I wrote this small perl script to perform this task:

#!/usr/bin/perl
# Move files to new subdirectories based on file name.
# CC BY SA 2015, Lieven Blancke
# my camera produces JPG files named IMG_yyyymmdd_nnnnnn.jpg
# I want to move these files to subdirectory per year, month and day
# IMG_20150723_233831.jpg -> 2015/07/23/IMG_20150723_233831.jpg
# IMG_20151001_174215.jpg -> 2015/10/01/IMG_20151001_174215.jpg
use strict;
use warnings;
use File::Copy;
use File::Path 'make_path';

my $directory = './';

opendir (DIR, $directory) or die $!;

while(my $file = readdir (DIR)) {
	# ignore files beginning with a period
        next if ($file =~ m/^\./);
	# only files, no directories
	next unless (-f "$file");
	# only process files like IMG_yyyymmdd_nnnnnn.jpg
	if ($file =~ /^IMG_([0-9]{4})([0-9]{2})([0-9]{2})_([0-9]{6})\.jpg$/) {
		print "$file -> $1/$2/$3/$file\n";
		# create the directory $1, $1/$2 and $1/$2/$3 in one go
		make_path("$1/$2/$3");
		# move the file to the directory
		move($file,"$1/$2/$3/$file") or die "Could not move file $1 to directory /$2/$3: $!";
	}
}

closedir(DIR);

Leave a Reply

Your email address will not be published. Required fields are marked *