#!/usr/bin/perl -w
#by Torben Menke
#http://www.entorb.net
# Properties:
# sorts images into subfolders named by their date of creation (images early in the morning are treated as if taken the day before
# not recursive in subfolders
# works on .jpg, .jpeg files
# renames .jpeg -> .jpg
#
# REQUIRES exif (debian package or similar...)
`exif --version` or die;
# TODO
# make the output nice (printf)
# use files.pl or copy subs from it
use strict;
use warnings;
use Time::Local;
#$time = timelocal($sec, $min, $hours, $mday, $mon, $year);
my @dirs; #list of directories
my @files; #list of files
my $str;
my $houroffset = 5; #if hour < offset $day=($day-1)
#how prefix and name are merged
my $joinstr = '/';
if (!@ARGV){
$dirs[0] = './';
}
else {
@_ = @ARGV;
&separate_df(@_);
}
while (@dirs){
my $dir = shift @dirs;
opendir DIR, "$dir";
#my @new_items = sort (grep {!/^\.\.?$/ } readdir DIR);
my @new_files = sort (grep { /\.jpe?g$/ } readdir DIR);
closedir DIR;
foreach $_ (@new_files) {
$_ = "$dir/$_";
if (-f $_){
s#//#/#;
push (@files,$_);
}
}
}
foreach my $file (@files){
my $filenew = '';
my $dirnew = '';
if ((my $prefix = &getprefix($file)) ne ''){
$_ = $file;
if (m#^(.*/)[^/]+$#){
$dirnew = $1;
}else {$dirnew = './';}
# dirnew ends with '/'
if ($joinstr =~ m#/#) {
# a subdir is going to be created
if (! -d $dirnew.$prefix){
mkdir $dirnew.$prefix;
}
}
m#([^/]+)$#;
$str = $1;
$str =~ tr/[A-Z]/[a-z]/;
$str =~ s/\.jpeg$/\.jpg/;
$filenew = $dirnew.$prefix.$joinstr.$str;
if (-f $filenew){
print "File $filenew already exists, skipped!\n";
} else{
print "$file\t->\t$filenew\n";
rename $file, $filenew;
}
} else {
print "No date information, file $file skipped!\n";
}
}
sub getprefix{
my $file = "@_";
#extract Date+Time using exif
$_ = `exif $file | egrep --text 'Date and Time '`;
print;
my ($sec,$min,$hour,$mday,$mon,$year) = (0,0,0,0,0,0);
s/^.*ASCII=([^@]*) @.*$/$1/;
if (m/(\d+)\D+(\d+)\D+(\d+)\D+(\d+)\D+(\d+)\D+(\d+)\D*$/){
($sec,$min,$hour,$mday,$mon,$year) = ($6,$5,$4,$3,$2,$1);
$sec = $sec + 0;
$min = $min + 0;
$hour = $hour + 0;
$mday = $mday + 0;
$mon = $mon + 0;
$year = $year + 0;
#if too early change date
if ($hour<$houroffset){
# month count starts at 0, year is saved as 1900 + x
my $time = timelocal($6, $5, $4, $3, ($2-1), ($1-1900));
$time = $time - 24*3600; #= -1 day
($sec,$min,$hour,$mday,$mon,$year) = localtime($time);
$mon = $mon + 1 ;
$year = $year + 1900;
}
return &genfoldername($year,$mon,$mday);
}#if (m/^(\d+)\D+(\d+)\D+(\d+)\D+(\d+)\D+(\d+)\D+(\d+)\D*$/)
else {return ''}
}
sub genfoldername{
my $output = '';
foreach $_ (@_){
if ($_>99){
$_ = $_ % 100; #modulo 100
}
if ($_<10){
$output.='0';
}
$output.=$_;
}
return $output;
}
# separates dirs and files
sub separate_df{
foreach $_ (@_){
if (-d $_){
push @dirs, $_;
}
elsif (-f $_ && m/\.jpe?g$/i){ #jpg, jpeg
push @files, $_;
}
}
}
sub br{
print "\n";
}
print "Job done!!!\n";
#$_ = <STDIN>;
Hope you found what you where looking for. Feel free to drop me a line
Torben