Reputation: 19516
I have some files whose names are like
Image 1.jpg
Image 2.jpg
Image 10.jpg
Image 11.jpg
Image 20.jpg
They are numbered in the exact order that I want them to appear, but windows takes them in this order when I do a dir
Image 1.jpg
Image 10.jpg
Image 11.jpg
Image 2.jpg
Image 20.jpg
If these were supposed to be frames in an animation, your animation would basically come out wrong.
I would like to pad the numbers with 0's. The format of the strings are always the same
PREFIX NUMBER.EXT
How can I pad the filenames so that I will get
Image 0001.jpg
Image 0002.jpg
Image 0010.jpg
Image 0011.jpg
Image 0020.jpg
Here is what I have done so far
echo off
Setlocal EnableDelayedExpansion
rem note the extra space at the end of "Image "
set prefix=Image
for %%F in (*.jpg) do (
set a=%%F
rem // strip the prefix
set a=!a:%prefix%=!
echo !a!
)
This removes the prefix. I would then pad the resulting filename with leading characters 0's and then rename the file.
Upvotes: 2
Views: 2552
Reputation: 63471
Instead of doing that prefix replacement, you could isolate the number like this: (remove echo
to enable the rename command)
@echo off
setlocal ENABLEDELAYEDEXPANSION
for %%A in (*.jpg) do (
for /f "tokens=1-3 delims=. " %%F in ("%%A") do (
set /a a=%%G
set zeros=
if !a! LSS 1000 set zeros=0
if !a! LSS 100 set zeros=00
if !a! LSS 10 set zeros=000
set "name=%%F !zeros!!a!.%%H"
echo ren "%%A" "!name!"
)
)
endlocal
Using set /a
does a numeric conversion, then you can use the extension comparator LSS
to compare the number and create the relevant padding, and finally reassemble the filename using its tokens. This particular snippet isn't generic - it only works if your prefix has no spaces or dots, and the name only has three main tokens. But you get the idea.
Upvotes: 2