Here's the script. Just put the script in your folder and run it.
@echo off & setlocal EnableDelayedExpansion
set a=1
for /f "delims=" %%i in ('dir /b *') do (
if not "%%~nxi"=="%~nx0" (
ren "%%i" "!a!"
set /a a+=1
)
)
If you want to keep the extensions, i.e. rename "IMG-12223.jpg", "IMG-12224.jpg", etc to "1.jpg", "2.jpg", etc, you may use the following script.
@echo off & setlocal EnableDelayedExpansion
set a=1
for /f "delims=" %%i in ('dir /b *.jpg') do (
ren "%%i" "!a!.jpg"
set /a a+=1
)
[Update] Here're explanations for the lines mentioned in Jack's comment.
setlocal EnableDelayedExpansion
In general, we want the variable a
to be delayed expansion when it's executed but not the line is read. Without it, the variable a
cannot get its increased value but always 1.
For the detail of EnableDelayedExpansion, please refer to the answer https://stackoverflow.com/a/18464353/2749114.
for /f "delims=" %%i in ('dir /b *.jpg')
Here dir
with /b
option, lists only file names of all jpg files.
The for
loop traverses and renames all jpg files.
For the delims
option, since the default delimiter character is a space, without the option delims=
, it fails with the image files with spaces in the file names. I.E. for an image file named "img with spaces.jpg", without the option, the value of %%i
is "img" but not the whole name "img with spaces.jpg", which is incorrect.
For for
loop, please refer to the page http://ss64.com/nt/for_f.html.
I have change it to if not "%%~nxi"=="%~nx0"
to be more accurate. And the codes attached have been updated.
It's actually used to avoid to rename the bat file itself. If we limit the renaming only upon "jpg" files, then the line is not needed.
%%~nxi
is the file name with extension for each file traversed. And %~nx0
is the running bat file with extension. For details, please refer to the page DOS BAT file equivalent to Unix basename command?.