Date: 24 Oct 2007 19:32:18 -0400 From: "Karl Vogel" <vogelke@pobox.com> To: andrew clarke <ozzmosis@gmail.com> Cc: freebsd-questions@freebsd.org Subject: Re: rename file based on file's timestamp Message-ID: <20071024233218.91214.qmail@kev.nowhere.usa> In-Reply-To: <20071024124508.GA17482@ozzmosis.com> (message from andrew clarke on Wed, 24 Oct 2007 22:45:08 %2B1000)
next in thread | previous in thread | raw e-mail | index | archive | help
>> On Wed, 24 Oct 2007 22:45:08 +1000, >> andrew clarke <ozzmosis@gmail.com> said: A> I have a series of files in a directory: A> -rw-r--r-- 1 ozzmosis ozzmosis 115201253 Jul 28 2006 209.mp3 A> -rw-r--r-- 1 ozzmosis ozzmosis 115201253 Jul 31 2006 212.mp3 A> Now I want to rename these so the new filenames are based on the file's A> timestamp, like so: A> -rw-r--r-- 1 ozzmosis ozzmosis 115201253 Jul 28 2006 2006-07-28.mp3 A> -rw-r--r-- 1 ozzmosis ozzmosis 115201253 Jul 31 2006 2006-07-31.mp3 A> I can write some Python code to do this, but maybe there is another way, A> perhaps using a shell script. Any thoughts? The script below is in Perl, but converting it to Python probably wouldn't be too difficult. -- Karl Vogel I don't speak for the USAF or my company Loch Ness monster surfaces in Jersey bathtub --Weekly World News headline --------------------------------------------------------------------------- #!/usr/bin/perl -w # Rename each regular file in the argument list using its modtime. # Add the inode number if that's not enough to create a unique file. use strict; foreach my $file (@ARGV) { # sanity checks. next unless -f $file; my ($inode, $mtime) = (stat(_))[1, 9]; die "$file: no mtime found\n" unless defined($mtime); # any file extension? my $ext = ''; $ext = "$1" if $file =~ m/(\.\w*)$/; # try date.extension, date.inode.extension, then give up. my ($day, $mon, $year) = (localtime($mtime))[3, 4, 5]; my $date = sprintf("%4.4d-%2.2d-%2.2d", $year + 1900, $mon + 1, $day); my $newfile = $date . $ext; if (-f $newfile) { $newfile = $date . '.' . $inode . $ext; } if (-f $newfile) { warn "unable to rename $file\n"; } else { unless (rename($file, $newfile)) { warn "rename $file to $newfile failed: $!\n"; } } } exit(0);
Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?20071024233218.91214.qmail>