Renaming files maintaining directory information in the file name

Been busy learning… well, a lot of stuff. Mostly Red Hat related (kickstart and virtualization).

Anyway. This isn’t something you usually want: renaming files from, for example, /path1/path2/path3/path4/path5/path6/file.ext to path5-path6-file.ext. I needed it for some photos I wanted to copy in one directory, while maintaining ordering and avoiding duplicate names to overwrite each other. Also, I didn’t want the full directory structure, only the meaningful last 2 directories.

Let’s see an example:

host % ls -R /home/velenux/Foto/
/home/velenux/Foto/2012/02/10:
IMG_20120209_133542.jpg

/home/velenux/Foto/2012/02/22:
_MG_8945.CR2  _MG_8953.CR2  _MG_8961.CR2  _MG_8971.CR2  _MG_8979.CR2
_MG_8946.CR2  _MG_8954.CR2  _MG_8963.CR2  _MG_8972.CR2  _MG_8980.CR2
_MG_8947.CR2  _MG_8955.CR2  _MG_8964.CR2  _MG_8973.CR2  _MG_8982.CR2

I conjured up this Perl script

#!/usr/bin/perl

use strict;
use warnings;
use Carp;

my($orig, $dest);

while (<>) {
        $dest = $_;
        chomp $dest;
        $orig = $dest;

        $dest =~ /([^\/]+)\/([^\/]+)\/([^\/]+)$/g;
        $dest = "$1-$2-$3";
        print "mv -vf \"$orig\" \"$dest\"\n";
}

This will be invoked like this:

host % find /path -print | perl genmove.pl > move-files.sh

The move-files.sh will look like this:

mv -vf "/home/velenux/Foto/2012/02/10/IMG_20120209_133542.jpg" "02-10-IMG_20120209_133542.jpg"
[...]

Edit the file if you need, then run it with bash move-files.sh