Krom Krom - 7 months ago 27
Perl Question

Using Perl to rename files in windows

My program needs to rename files that end like this

file(1)
file(2)
file(3)

I want them to be renamed to this

file_1
file_2
file_3

I attempted this in c++ but that does not seem efficient. I think Perl would be great for it but do not know where to start even.

Answer
#!/usr/bin/perl
use strict;
use warnings;

my $dir =       'folder';
my @dir =       ();

opendir(DIR, $dir);
@dir    =       readdir(DIR);
closedir(DIR);

foreach my $file (@dir) {
    my $f=$file;
    $f =~ s/\(/_/;
    $f =~ s/\)//;
    rename "$dir/$file", "$dir/$f";
}

The \( in s/\(/_/ is matching the "(" in the filename file(1) and replacing with "_", so $f =~ s/\(/_/; makes $f become file_1). The \) in s/\)// is matching the ")" in the filename file_1) and replacing with "" (nothing), so $f =~ s/\)//; makes $f become file_1.

Comments