You are not logged in.
Pages: 1
I'm trying to pad out files so the number is always 3 digits. So
image_1 -> image_001
image_2 -> image_002
image_10 -> image_010
image_11 -> image_011
image_100 -> image_100
image_101 -> image_101
And I'm trying to do this without cd'ing into the directoy. The following command works in most cases
perl-rename 's/\d+/sprintf("%03d", $&)/e' <DIRNAME>/*
However if the DIR contains digits it obviously tries to change the digits in the DIR name instead of the filename.
I've tried
perl-rename -n 's/(.*)_(\d+)/sprintf("%s_%03d",$1,$2)/' <DIRNAME/*>
But this just returns
image_9.jpg -> sprintf("%s_%03d",image,9).jpg
Any ideas what the correct format for the sprintf would be or is the rror else where.
TA
Last edited by kurt (2016-04-25 21:17:13)
Offline
This seems to work, both when run with just filenames, and when run with a directory or several directories in the name:
perl-rename -n '($d,$f) = m{(.*/)?(.*)}; $f =~ s/\d+/sprintf("%03d", $&)/e; $_ = $d.$f'
You can also use 'find' to call perl-rename. 'find' has an option "-execdir" where it first changes into a directory before it calls the command you want it to run, and then you'll always have names like "./image_1.png" going into perl-rename.
EDIT:
Here's another way that seems to work:
$ perl-rename -n 's{^(.*/)?(.*_)(\d+)([.][^.]+)$}{sprintf "%s%s%03d%s", $1, $2, $3, $4}e' t/images_*/*
t/images_1/image_10.jpg -> t/images_1/image_010.jpg
t/images_1/image_11.jpg -> t/images_1/image_011.jpg
t/images_1/image_1.jpg -> t/images_1/image_001.jpg
t/images_1/image_2.jpg -> t/images_1/image_002.jpg
t/images_1/image_3.jpg -> t/images_1/image_003.jpg
$ cd t/images_1
$ perl-rename -n 's{^(.*/)?(.*_)(\d+)([.][^.]+)$}{sprintf "%s%s%03d%s", $1, $2, $3, $4}e' *
image_10.jpg -> image_010.jpg
image_11.jpg -> image_011.jpg
image_1.jpg -> image_001.jpg
image_2.jpg -> image_002.jpg
image_3.jpg -> image_003.jpg
Last edited by Ropid (2016-04-24 19:11:53)
Offline
$ perl-rename -n 's{^(.*/)?(.*_)(\d+)([.][^.]+)$}{sprintf "%s%s%03d%s", $1, $2, $3, $4}e' t/images_*/*
Thankyou - This was very helpful. I went for
perl-rename -n 's/(.*_)(\d+)/sprintf "%s%03d", $1, $2/e'
In the end
Offline
Pages: 1