How to rename multiple files with one command on Windows, Linux, or Mac?
Given many, many files named like this: my_file_1.php, how can I rename them to be named like this: my-file-1.php
use strict; use warnings; use 5.010; my $dir = shift or die "Usage: $0 DIR"; use Path::Iterator::Rule; use Path::Tiny qw(path); my $rule = Path::Iterator::Rule->new; for my $file ( $rule->all( $dir ) ) { #say $file; my $pt = path $file; #say $pt->basename; if ($pt->basename =~ /\.php$/) { my $newname = $pt->basename; $newname =~ s/_/-/g; #say "rename " . $pt->path . " to " . $pt->parent->child($newname); rename $pt->path, $pt->parent->child($newname); } }
Save this as rename.pl and then run it on the command line perl rename.pl path/to/dir.
Alternatively, save this as rename.pl, replace the my $dir ... line by my $dir = "/full/path/to/dir"; and then you can run it without passing the directory name on the command line.
On Windows the path name should be either using slashes: my $dir = "c:/full/path/to/dir";, or using pairs of back-slashes: my $dir = "c:\\full\\path\\to\\dir";.
Path::Iterator::Rule will allow us to traverse the directory tree, so we can rename files in the whole tree.
Path::Tiny helps us extracting the directory name and building the new name.
Some commented out print-statement were left in, to make it easier to follow what's happening.

Published on 2013-12-08