>> On Wed, 24 Oct 2007 22:45:08 +1000, 
>> andrew clarke <[EMAIL PROTECTED]> 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);

_______________________________________________
freebsd-questions@freebsd.org mailing list
http://lists.freebsd.org/mailman/listinfo/freebsd-questions
To unsubscribe, send any mail to "[EMAIL PROTECTED]"

Reply via email to