CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
Searching for the numeric characters in a filename and adding to the numeric part of a filename

 



adaykin
Novice

Jul 9, 2007, 1:33 PM

Post #1 of 3 (492 views)
Searching for the numeric characters in a filename and adding to the numeric part of a filename Can't Post

Say I want to go through a directory and find all files that start with three numbers, e.g. "001" and then convert the "001" to an integer, and then add n to it. The files will have names like: "001 - TestCase.t" and I would want it changed to something like "003 - TestCase.t" I have an idea, I would start out by doing:


Code
 
while (defined($file = readdir(BIN))){
my @files = grep {/*[\d]{3}*/} readdir BIN;
close BIN;
foreach my $fileNameToInt(@files){
## Convert first 3 chars of file to int, add $n to the int, replace the old value with the new value to update file name ##
}
}


This is similar to the last program I wrote (which I did get working btw) but I don't know much about strings/ints in perl.
------------------------------------------------------------

New Horizon Designs <-- My site, just updated the GUI to a PHP Nuke interface


KevinR
Veteran


Jul 9, 2007, 7:36 PM

Post #2 of 3 (490 views)
Re: [adaykin] Searching for the numeric characters in a filename and adding to the numeric part of a filename [In reply to] Can't Post

Untested code so take precautions:


Code
opendir (BIN, 'thedirectory') or die "$!";  
my @files = grep {/^\d{3}/} readdir BIN;
close BIN;
foreach my $file (@files){
my $old = $file;
$file =~ /^(\d{3})/;
$int = $1 + 2;
$file =~ s/^(\d{3})/$int=sprintf("%03.f",$int)/e;
rename($old,$file);
}

-------------------------------------------------


adaykin
Novice

Jul 10, 2007, 6:44 AM

Post #3 of 3 (484 views)
Re: [KevinR] Searching for the numeric characters in a filename and adding to the numeric part of a filename [In reply to] Can't Post

Thank you so much! It works perfectly!
------------------------------------------------------------

New Horizon Designs <-- My site, just updated the GUI to a PHP Nuke interface

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives