exif_rename.pl
author Peter Gervai <grin@grin.hu>
Sat, 02 Oct 2021 15:04:41 +0200
changeset 11 5c38653bd7e7
parent 0 624a9ab34425
permissions -rwxr-xr-x
perlgrok.pl: sanitize labels even if there was no macro replacement (manual capture groups)

#!/usr/bin/perl -w
#
# set date from exif info
# $Id: exif_rename.pl 208 2003-09-15 12:24:09Z grin $
#
# (c)2003, Peter Gervai
#


use POSIX qw( strftime );

my $exifprog="exiftags";
my $filepattern = qr/^(.+)\.jpg/i;
my $FNAME = "pic";
my $FEXTENSION = "jpg";

my $into_current_dir = 1;

my $DEBUG=0;

my $dir = $ARGV[0];
if( !defined($dir) || !-d $dir ) {
    print "hasznalat: $0 <start directory>\n\n";
    exit;
}


my %files;
&walk_files( $dir, '', \%files );

for my $key (sort keys %files) {
    
    print "($key) ", $files{$key}[0], '->', $files{$key}[1], "<<\n" if $DEBUG;
    print "mv \"$files{$key}[0]\" \"$files{$key}[1]\"\n";
    
}


sub walk_files {
    my ($base, $sdir, $rfiles) = @_;
    print "Walking dir $base; $sdir...\n";
    
    if( !-r "$base/$sdir" ) {
        print "Nem olvashato $base/$sdir!\n";
        return undef;
    }
    
    opendir( D, "$base/$sdir" );
    my @entries = grep { !/^\.\.?$/ } readdir( D );
    closedir( D );
    foreach my $entry (@entries) {
        if( -f "$base/$sdir/$entry" && $entry =~ /$filepattern/ ) {
            # process file
            my $newname = &get_newname( "$base/$sdir", $entry, $1 );
            
            my $cnt = 1;
            my $oname = $newname;
            $newname .= ".$FEXTENSION";
            while( defined( $rfiles->{$newname} ) ) {
                print "CLASH $cnt\n" if $DEBUG;
                $newname = "$oname-$cnt.$FEXTENSION";
                $cnt++;
            }
            
            $rfiles->{$newname} = ["$base/$sdir/$entry", $newname];
            
            print "Got file $base; $sdir; $entry.\n" if $DEBUG;
            
        } elsif( -d "$base/$sdir/$entry" ) {
            # walk subdir
            &walk_files( $base, "$sdir/$entry", $rfiles );
        }
    }
}



sub get_newname {
    my ($base, $entry, $basename) = @_;
    my $time = &get_exif_time( "$base/$entry" );
    
    my $newname;
    if( $into_current_dir ) {
        $newname = "./$FNAME-$time";
    } else {
        $newname = "$base/$FNAME-$time";
    }
    
    return $newname;
}


sub get_exif_time {
    my $file = shift;
    
    if( -f $file ) {
        my $res = qx( $exifprog "$file" 2> /dev/null );
        if( $res =~ m/Image Created: (\S+ \S+)/ ) {
            #print "res=$_>>$1<<\n";
            # s m h md m y
            my @d = split /[: ]/, $1;
            #print "mon:", join(",", @d) , "<<\n";
            $d[1] -= 1;
            $d[0] -= 1900;
            return strftime("%Y.%m.%d-%H.%M.%S",  @d[5,4,3,2,1,0] );
        }
    }
    return "none";
}