Perl – Script to rename files in a Windows subdirectory

perlvbscript

Can someone suggest a script to rename a bunch of files in a Windows subdirectory with filenames having spaces to them having underscores. For example if the filename is

abc xyz.pdf

It should be

abc_xyz.pdf

Best Answer

Perl: Use File::Find for recursive finding and actioning on files.

Please note that you need to be careful about: Don't rename DIRECTORIES that have underscore, thus File::Basename.

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

find ({ 'wanted' => \&renamefile }, 'X:\my\sub\dir');

sub renamefile {
    my $file = $_;
    return unless (-f $file);   # Don't rename directories!
    my $dirname = dirname($file); # file's directory, so we rename only the file itself.
    my $file_name = basename($file); # File name fore renaming.
    my $new_file_name = $file_name;
    $new_file_name =~ s/ /_/g; # replace all spaces with underscores
    rename($file, File::Spec->catfile($dirname, $new_file_name))
        or die $!; # Error handling - what if we couldn't rename?
}
Related Topic