
KevinR
Veteran

Jun 27, 2007, 12:17 PM
Post #6 of 13
(4059 views)
|
Re: [adaykin] Hey I want to rename a certain part of a file
[In reply to]
|
Can't Post
|
|
OK, clearly you have a problem with the logic of your code:
while($file = readdir BIN && $file=~/*$wordToBeReplaced*/) { foreach $file (@NAMES) { first you assign $file the return value of the expressions on the right in the "while" loop condition, but then you assign it the value of each element of @NAMES in the "foreach" loop. What you should do is a get a list of the files that match your regexp to begin with. Assuming no other checks are necessary:
opendir(BIN,"path/to/directory") or die "$!"; my @files = grep {/$wordToBeReplaced/} readdir BIN; close BIN; Now you loop through @files and change the names using another regexp:
opendir(BIN,"path/to/directory") or die "$!" my @files = grep {/$wordToBeReplaced/} readdir BIN; close BIN; foreach my $oldfile (@files) { my $newname = $oldfile; $newname =~ s/searchpattern/replacepattern/; rename($oldname,$newname) or warn "Couldn't rename $oldname to $newname: $!\n"; } rename() will work with only the filenames if you are in the directory where the files are, otherwsie you have to prepend the names with the full path to the directory:
rename("path/to/$oldname","path/to/$newname") and of course changing the filename is subject to the restrictions of your operating system, ie: open files, pe-existing files, etc. -------------------------------------------------
|