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

Batch Script (Explicit)

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

Further Resources

  • EnableDelayedExpansion

    Delayed Expansion will cause variables within a batch file to be expanded at execution time rather than at parse time, this option is turned on with the SETLOCAL EnableDelayedExpansion command.


    When delayed expansion is in effect, variables can be immediately read using !variable_name! you can also still read and use %variable_name% that will show the initial value (expanded at the beginning of the line).

  • For

    Variable Substitutions (FOR /?)

    In addition, substitution of FOR variable references has been enhanced. You can now use the following optional syntax:

    %~I - expands %I removing any surrounding quotes (")
    %~fI - expands %I to a fully qualified path namey
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like