I have a folder "C:\Pictures\test" which contains about 200 photos and nothing else. (Actually, until I get this code working, it contains only 2 photos.) The photos are different file types (.png, .jpg, etc) and their names are all numbers. I'd like to add a fixed number to those file names, e.g. "4500.png" -> "4700.png" and "4501.jpg" -> "4701.jpg". I expect this situation to recur so I'd really like to automate it. Therefore, a few hours ago, I learned Windows batch files exist. Please be gentle -- I barely even know how to ask about the things I don't understand. (Two hours of googling preceded this question. Some of it was even helpful.)
By cobbling together code found elsewhere, I've written this code (note that I don't really care about catching any exceptions):
::renames all files in a folder by adding a fixed value
@ECHO OFF
SET /p addnum="Enter number to add to all photo names: "
SET /p loc="Enter folder location to navigate to: "
CD %loc%
FOR /F %%i IN ("*.*") DO (SET newname = SET /a %%i+%addnum% & SET file_name = %newname%)
PAUSE
Everything through the CD
works. But the FOR
statement line doesn't (small wonder -- this is the only part of the code I didn't copy from somewhere!). When I run it, it doesn't complain, but it doesn't do anything either -- no output; no change in the file names.
What I want the DO
statement to do:
newname
which is the file name %%i
(remember, this is a number) + addnum
%%i
to <newname>.<extension>
How should I actually write this batch file?
The following batch file could be used which has only a rudimentary error handling.
@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "addnum=100"
set "loc=."
set /P "addnum=Enter number to add to all photo names: "
set /P "loc=Enter folder location to navigate to: "
pushd "%loc%"
if errorlevel 1 goto EndBatch
setlocal EnableDelayedExpansion
for /F "eol=| delims=" %%I in ('dir *.jpg *.png /A-D /B 2^>nul ^| %SystemRoot%\System32\findstr.exe /I /R "^[0123456789][0123456789]*\.jpg$ ^[0123456789][0123456789]*\.png$"') do (
set /A NewName=%%~nI + addnum
ren "%%I" "!NewName!%%~xI"
)
endlocal
popd
:EndBatch
endlocal
pause
To understand the commands used and how they work, open a command prompt window, execute there the following commands, and read the displayed help pages for each command, entirely and carefully.
cd /?
dir /?
echo /?
endlocal /?
findstr /?
for /?
goto /?
if /?
pause /?
popd /?
pushd /?
ren /?
set /?
setlocal /?