How can I write Windows batch file command with loop and % operator?
It's rather complicated, because of the way variable expansion in loops works in batch files. Batch files do have their own for
construct; no need to mess around with goto
s. %%
is the modulo operator in batch files, as %
is reserved for expansion of variables.
This code works for me:
@echo off
setlocal enabledelayedexpansion
for /l %%i in (0,1,99) do (
set /a remainder = %%i %% 10
if !remainder! == 0 (
echo something
) else (
echo %%i
)
)
endlocal
Modulo can be done with set /a
. Loops can be done with goto
, just like how you convert those for
loops into goto
in C
@echo off
set "i=0"
:loop
if %i% equ 100 goto :endfor
set /a "mod=i %% 10"
if %mod% equ 0 (
echo something %mod%
) else (
echo %i%
)
set /a "i+=1"
goto :loop
:endfor
Notice that rem
is a command for starting a comment so using rem
in the script may result in undesired behavior
The loop can be made simpler with for /l
but now you have to enable delayed expansion because the whole body of for
is parsed at once