Created
June 22, 2018 06:55
-
-
Save bcc32/7f994995ecf6fe280d91bed2233564e8 to your computer and use it in GitHub Desktop.
A simple perl script to rename files based on their modification times.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use 5.016; | |
use warnings; | |
use autodie; | |
use File::Spec; | |
use File::stat; | |
use POSIX qw(strftime); | |
# rename_noclobber($old, $new); | |
# | |
# Attempts to rename the file $old to new path $new, without overwriting an | |
# existing file. It is not 100% reliable, and may overwrite files if multiple | |
# instances of this program are running, for example. | |
sub rename_noclobber { | |
my ($old, $new) = @_; | |
# XXX RACE CONDITION | |
if (-e $new) { | |
warn "'$new' already exists, skipping '$old'\n"; | |
return; | |
} | |
rename $old => $new; | |
} | |
use constant USAGE => <<EOF; | |
Usage: perl rename-to-mtime.pl FILE... | |
Rename files based on their modification times. | |
EOF | |
sub main { | |
# die if there are no arguments | |
die USAGE unless @ARGV; | |
for my $path (@ARGV) { | |
my ($vol, $dir, $file) = File::Spec->splitpath($path); | |
my $stat = stat($path); | |
if (! defined $stat) { | |
warn "cannot stat '$path': $!\n"; | |
next; | |
} | |
# determine mtime | |
my $mtime = strftime '%Y%m%dT%H%M%SZ', gmtime $stat->mtime; | |
# determine file extension | |
$file =~ /(?<ext> | [.][^.]* ) \z/xms; | |
my $new_path = File::Spec->catpath($vol, $dir, $mtime . $+{ext}); | |
if ($path eq $new_path) { | |
# already named correctly, so skip | |
next; | |
} | |
rename_noclobber $path, $new_path; | |
} | |
} | |
main unless caller; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment