Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I increment a filename in batch?

I cannot understand what is wrong with my code. I followed everything I found on the internet but if I run the code, it returns "the syntax was incorrect" or something like that. It basically increments a filename if the basename exists. Can you show me what is wrong with my code and how do I correct it?

:MainProcessNew
cd C:\Users\%USERNAME%\Documents
for %%G IN (*.json) do (
set file = %%G
)
set "baseName=data"
set "n=0"

:loop
set /a n+=1
if exist "%baseName%%n%.json (
goto loop
)

echo.>"C:\Users\%USERNAME%\Documents\data%n%.json"
like image 856
Jezreel Martin Avatar asked Nov 24 '25 18:11

Jezreel Martin


1 Answers

Use this batch code:

:MainProcessNew
cd /D "%USERPROFILE%\Documents"
for %%G in (*.json) do set "FileName=%%G"

set "BaseName=data"
set "FileNumber=0"

:FileNameLoop
set /A FileNumber+=1
if exist "%BaseName%%FileNumber%.json" goto FileNameLoop

echo/>"%USERPROFILE%\Documents\%BaseName%%FileNumber%.json"

The main mistake is the missing double quote in IF condition line.

But there are also other mistakes and code lines which could be improved.

Don't use C:\Users\%USERNAME% because the profile directory of a user can be also on another drive than drive C:. Use instead the value of the predefined environment variable USERPROFILE.

The path to documents folder of the current user can contain 1 or more spaces, for example when the user name contains a space. Therefore always enclose user profile related folder paths in double quotes.

The command CD should be used always with /D to change also the current drive if it is not 100% guaranteed that current directory of batch process and new current directory are on same drive.

Never assign a value to an environment variable with spaces around equal sign, see Why is no string output with 'echo %var%' after using 'set var = text' on command line? for an explanation of this common mistake.

Don't define a command block with parentheses for the commands FOR and IF if just 1 command should be executed as those two commands are originally designed for running only 1 command.

It is advisable to use good variable names in CamelCase notation. It is hard to search for n to find all occurrences of that environment variable, but is very easy to search for FileNumber.

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

  • cd /?
  • echo /?
  • for /?
  • goto /?
  • if /?
  • set /?
like image 59
Mofi Avatar answered Nov 27 '25 09:11

Mofi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!