You appear to be bogged down matching all sorts of things that you're not interested in. You only want to match the "00001" in "XYZ12345_X05_20110805_9999999_00001.TXT". This regex does that:
/(?<=_)00001(?=[.]\w+$)/
Then, you want to replace that with a random number. Your sprintf format indicates: seven digits, right-aligned, zero-padded. As the "%d" in the sprintf format already indicates an integer, you don't need to use int. Assuming zero is not a valid random number for your requirements, the range is "0000001" to "9999999". You can get that range with:
rand(9999999)+1
So, putting all that together, we get:
s/(?<=_)00001(?=[.]\w+$)/sprintf "%07d" => rand(9999999)+1/e
[Note: your "int( rand(100000)) + 999999" will produce this range: "0999999" to "1099998". I'm guessing that's not really what you want; however, if you want some different from the range I suggested, see rand for the values it returns and adjust accordingly.]
I ran some tests (which included edge cases) with this code:
$ perl -Mstrict -Mwarnings -le ' my @test_filenames = qw{ XYZ12345_X05_20110805_9999999_00000.TXT XYZ12345_X05_20110805_9999999_00001.TXT XYZ12345_X05_20110805_9999999_00002.TXT XYZ12345_X05_20110805_9999999_00001x.TXT XYZ12345_X05_20110805_00001_00001.TXT XYZ12345_X05_20110805_00001_00001xxx.TXT }; for (@test_filenames) { s/(?<=_)00001(?=[.]\w+$)/sprintf "%07d" => rand(9999999)+1/e; print; } '
Here's one sample output:
XYZ12345_X05_20110805_9999999_00000.TXT XYZ12345_X05_20110805_9999999_1656320.TXT XYZ12345_X05_20110805_9999999_00002.TXT XYZ12345_X05_20110805_9999999_00001x.TXT XYZ12345_X05_20110805_00001_0901076.TXT XYZ12345_X05_20110805_00001_00001xxx.TXT
-- Ken
In reply to Re: Filename change with regular expression
by kcott
in thread Filename change with regular expression
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |