Enric Agud Pique Enric Agud Pique - 6 months ago 10
Perl Question

modify name of files in a directory

I need to modify part of the name of files in a directory, I use the following code, but it only prints in terminal the modification of string but not save it

my @files = glob("*.grb *.out");
foreach my $file (@files) {
print "$file\n";
s/d02/d03/g;
}


How can I get them with the string d03 instead ofg d02?

Answer
my @files = glob("*.grb *.out");
foreach my $file (@files) {
    (my $newName = $file) =~ s/d02/d03/g;
    rename $file, $newName;
}

Or if you have Perl 5.14+,

my @files = glob("*.grb *.out");
foreach my $file (@files) {
    my $newName = $file =~ s/d02/d03/gr;
    rename $file, $newName;
}

This will rename all *d02* files to *d03* files (on-disk).

Comments