Script to rename files with the name of the folder?

I want to recursively rename files by prepending the folder name in front of it. Ex: c:\test\foo\a.txt would become c:\test\foo\foo-a.txt.

Answers


The following Perl script may work for you:

#!/usr/bin/env perl

use strict;
use warnings;

use File::Basename;
use File::Find;
use File::Spec;

sub rename {
    my ($dir_name) = ( File::Spec->splitdir($File::Find::dir) )[-1];
    my $file_name = basename $_;
    if ( -f $_ ) {
        $file_name = "$dir_name-$file_name";
        rename $_, File::Spec->catdir( $File::Find::dir, $file_name );
    }
}

find { 'wanted' => \&rename, 'no_chdir' => 1 }, 'C:/test/foo';
References:

use File::Find::Rule qw( );
use Path::Class      qw( dir file );

my $base = dir('.')->absolute;
for my $qfn (File::Find::Rule->file->in($base)) {
   my $file = file($qfn);
   my $dir  = $file->dir;

   my $src = $file;
   my $dst = $dir->file($dir->basename . '-' . $file->basename);

   if (-e $dst) {
      warn("Can't rename $src to $dst: Already exists\n");
   } 
   elsif (!rename($src, $dst)) {
      warn("Can't rename $src to $dst: $!\n");
   } 
}

Need Your Help

Something fishy about AWS S3 SSL deprecation and iOS SDK

security ssl amazon-web-services amazon-s3 awsiossdk

I got this email from Amazon saying that some of my app's use SSL to access S3 buckets. After I contacted their support, they gave me a list of clients, which points to my iOS app running on iOS7/8...

Way to parse information from email to database

php sql ruby-on-rails sql-server vb.net

I have an email account that receives various requests to get free materials, for different items. These emails will usually contain name, item, quantity of item, address, state, zip. What makes it

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.