Tuesday, March 22, 2011

Batch Renaming

I have a bunch of MTS files that I get from my camcorder, and frankly I don't have any interest in sitting down and renaming each file by hand, in perl this is a pretty simple case, I decided I wanted to name them based on their creation date, then number of file in that creation date. I still would say read over this script and make sure you understand what it is doing and then go ahead and use it.

This can easily be modified to work with any kind of file, but I was only concerned about my video camera files. if you want change the <*.MTS *.m4v> to whatever file types you want!

Here is the code:
# Written by Tyson Bailey
# with date/string creation from: http://www.seto.org/mt- diary/archives/2005/11/using_perl_to_d.html
use File::stat;
use Time::localtime;
@files = <*.MTS *m4v>;
$extension = "";
foreach $file (@files)
    # get date/time
    $date_string = ctime(stat($file)->mtime);
    # break it up into an array.
    @date = split('\s+',$date_string);
    $i = 0;
    # figure out file extension
    if ($file =~ m/.m4v$/)
        $extension = "m4v";
        $extension = "MTS";
    # Filename format MAR_05_2011_x.extension
    while (-e "@date[1]_@date[2]_@date[4]_$i.$extension")
    # just to be safe
    $base_name = quotemeta("@date[1]_@date[2]_@date[4]_");
    # if our filename already exists we really don't want to try renaming it.
    if ($file !~ m/$base_name/i)
        print "Didn't Matched: $base_name\n";
        print "Renaming: " . $file . "\n";
        print "To: @date[1]_@date[2]_@date[4]_$i.$extension\n";
        rename("$file", "@date[1]_@date[2]_@date[4]_$i.$extension");
        print "Not Renaming: $file\n";

Big thanks to:
for formatting my source code!

No comments:

Post a Comment