Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
Let's assume we have three groups of files, a, b and c:
a1.jpg
a2.jpg
...
a50.jpg
b1.jpg
b2.jpg
...
b150.jpg
c1.jpg
c2.jpg
...
c20.jpgLet us assume that each group of a, b or c can have at most 999 files. We want these files to be renamed such that:
* c files are prefixed with 0-, a files are prefixed with 1-, and b files are prefixed with 2- to create a desired alphabetical order.
* The digit components of the filenames are completed to three digits using preceding zeroes if necessary.
So the above files would be renamed to the following:
0-c001.jpg
0-c002.jpg
...
0-c020.jpg
1-a001.jpg
1-a002.jpg
...
1-a050.jpg
2-b001.jpg
2-b002.jpg
...
2-b150.jpgHow would one go about doing this with a batch file? Thanks.

Hi
Try This
I inserted echo before the ren command for safety.@echo off
setlocal enabledelayedexpansionfor /f "tokens=*" %%a in ('dir /b *.jpg') do (
set FName=%%~na
set FChar=!FName:~,1!
set /a Num=!FName:~1!
if !Num! LSS 10 set Num=0!Num!
if !Num! LSS 100 set Num=0!Num!
if !FChar!==c set NName=0-!FChar!!Num!
if !FChar!==a set NName=1-!FChar!!Num!
if !FChar!==b set NName=2-!FChar!!Num!
echo ren !FName!.jpg !NName!.jpg
)

Thank you for your help. The code works great. I especially like the clever bit where you padded the numbers by testing iteratively in two lines. It would have taken me a lot more lines.
There was a little bug where, for *.jpg files in the same directory that don't have any of the predetermined prefixes (a, b or c) the batch file tried to name all of them 0-c001.jpg. I think it was doing that because NName was uninitialized and it tried to initialize NName somehow. It doesn't make sense but that's what it did. I fixed it by adding a couple of lines to initialize NName and then test for it as follows:
@echo off
setlocal enabledelayedexpansionfor /f "tokens=*" %%a in ('dir /b *.jpg') do (
set FName=%%~na
set NName=!FName!
set FChar=!FName:~,1!
set /a Num=!FName:~1!
if !Num! LSS 10 set Num=0!Num!
if !Num! LSS 100 set Num=0!Num!
if !FChar!==c set NName=0-!FChar!!Num!
if !FChar!==a set NName=1-!FChar!!Num!
if !FChar!==b set NName=2-!FChar!!Num!
if not !NName!==!FName! echo ren !FName!.jpg !NName!.jpg
)

![]() |
![]() |
![]() |

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |