Batch Script for Loop and If Statement Not Interacting Properly

For archiving purposes, I have one directory full of files called note_1.txt, note_3.txt, note_4.txt, etc. I am writing a script to find the biggest number N among those files, and rename a new note.txt file to note_N+1.txt.

I am using a batch for loop for the first time and can't make it work properly. I tried replacing % by ! but I am not sure I understand how it works.

SETLOCAL ENABLEDELAYEDEXPANSION
SET "maxfile=1"
for /f %%i in ('dir /b note_*.txt') do (
    SET archivename=%%~ni
    SET archivenumber=%archivename:~5%
    if %archivenumber% GTR %maxfile% SET /a maxfile=%archivenumber%+1
)
echo %maxfile%
ENDLOCAL
1

1 Answer

I just added the ! to the variables within the FOR loop to ensure they are all expanded at execution time within the loop to ensure new set values are read accordingly to help get the final !maxfile! value as per each loop iteration.

Furthermore, I added the CD /D "%%~F0" to the line above the start of the FOR loop to ensure the directory is changed to the directory the script resides since you're not explicitly specifying the directory in your command example but I added an explicit example script below as well.

Batch Script (Implicit)

SETLOCAL ENABLEDELAYEDEXPANSION
SET "maxfile=1"
cd /d "%%~F0"
for /f %%i in ('dir /b note_*.txt') do (
    SET "archivename=%%~ni"
    SET "archivenumber=!archivename:~5!"
    if !archivenumber! GTR !maxfile! SET /a maxfile=!archivenumber!+1
)
echo !maxfile!
ENDLOCAL
Marcus Vance

Marcus Vance

Cybersecurity & Digital Privacy Researcher

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.