Perl is the right tool for this job, but given the potential for creating a big mess of things, I would perform the operation in stages:
1. Generate a list of the files you want to rename.
2. Generate a list of the renamings you want to perform.
3. Execute the renamings.
Then at each stage you can verify that you are going to do what you want to do.
For step 1, just assemble a list of the relavent file names into a text file, one path per line.
For step 2, read in the contents of the file generated in step 1 and output another file consisting of pairs of file names.
For step 3, read in the output of step 3 and execute the renaming.
E.g.:
Output of step 1:
file1
file2
file3
Output of step 2:
file1 new-file-1
file2 new-file-2
file3 new-file-3
Then you can visually inspect the output at each stage to verify that what you want to happen will happen. I always do this before I make big changes to a tree of files.
The only tricky part is step 2 - you have to decide how to encode a pair of path names into a single line (or use some other encoding). Usually this will require knowing that a certain character, e.g. a space, will not occur in your list of file names. Or perhaps you can use a sequence of characters (like '-->') which you know doesn't occur in your list of file names. So the script for step 2 might look something like:
while (<>) {
chomp;
... derive $new from $_ ...
print $_, ' --> ', $new, "\n"; # use ' --> ' as the delimiter
}
and the beginning part of the script for step 3 looks like:
while (<>) {
chomp;
my ($old, $new) = split(' --> ', $_, 2);
unless (rename $old, $new) {
warn "unable to rename $old to $new: $!\n";
}
}
As for how to derive the new names from the old names, that all depends on what kind of renaming you need to perform. Using regular expression or looking up names in a hash are potentially good ways of doing it.
Generating the files can be done either in perl or with just shell tools like find and grep.
Hope this helps.
|