I suggest to use this code:
REM Run model outputs
if not exist iteration.txt set "iter=1" & goto CopyFile
set "iter="
for /F "delims=" %%i in (iteration.txt) do if not defined iter set "iter=%%i"
set /A iter+=1
:CopyFile
copy run1_Diagnostics.csv storefilesfolder\%iter%_Diagnostics.csv
>iteration.txt echo %iter%
There is also another method to read the first line of a text file and assign it to an environment variable:
REM Run model outputs
if not exist iteration.txt set "iter=1" & goto CopyFile
set "iter="
set /P iter=<iteration.txt
set /A iter+=1
:CopyFile
echo copy run1_Diagnostics.csv storefilesfolder\%iter%_Diagnostics.csv
>iteration.txt echo %iter%
Both batch files first check if the file iteration.txt
exists at all in current directory.
The environment variable iter
is defined with value 1
if the file does not exist.
Otherwise the first line is read from the file and assigned to environment variable iter
using command FOR or an input redirection from file on prompting for value of the environment variable using command SET with option /P
.
The value read from file is incremented by one using command SET with option /A
which means the new value of environment variable iter
is the result of an arithmetic expression. set /A
is the only method supported by Windows command line interpreter to do simple mathematical or binary operations on 32-bit signed integer values. The value of iter
is 1
if the string read from file is not a valid 32-bit signed integer.
Next the file is copied with using initial value 1
or the value read from file iteration.txt
incremented by one.
.\
is not really necessary to specify the current directory. It is safe to omit those two characters if the file or folder is in current directory.
The last command line outputs the current iteration value to handle STDOUT which is redirected to file being created or overwritten in case of existing already.
The redirection operator and the file name is specified here left to command ECHO which outputs the number because of echo %iter%>iteration.txt
would not work for the numbers 1
to 9
. And using echo %iter% >iteration.txt
writes the space character between number and redirection operator >
also into the file as trailing space which should be avoided here.
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.
copy /?
echo /?
for /?
goto /?
if /?
rem /?
set /?
Read also the Microsoft article about Using Command Redirection Operators for an explanation of redirection operators <
and >
and single line with multiple commands using Windows batch file for an explanation of operator &
.