Batch Script Loop


Answer :

for /l is your friend:

for /l %x in (1, 1, 100) do echo %x 

Starts at 1, steps by one, and finishes at 100.

Use two %s if it's in a batch file

for /l %%x in (1, 1, 100) do echo %%x 

(which is one of the things I really really hate about windows scripting)

If you have multiple commands for each iteration of the loop, do this:

for /l %x in (1, 1, 100) do (    echo %x    copy %x.txt z:\whatever\etc ) 

or in a batch file

for /l %%x in (1, 1, 100) do (    echo %%x    copy %%x.txt z:\whatever\etc ) 

Key:
/l denotes that the for command will operate in a numerical fashion, rather than operating on a set of files
%x is the loops variable
(starting value, increment of value, end condition[inclusive] )


And to iterate on the files of a directory:

@echo off  setlocal enableDelayedExpansion   set MYDIR=C:\something for /F %%x in ('dir /B/D %MYDIR%') do (   set FILENAME=%MYDIR%\%%x\log\IL_ERROR.log   echo ===========================  Search in !FILENAME! ===========================   c:\utils\grep motiv !FILENAME! ) 

You must use "enableDelayedExpansion" and !FILENAME! instead of FILENAMEFILENAME. In the second case, DOS will interpret the variable only once (before it enters the loop) and not each time the program loops.


Template for a simple but counted loop:

set loopcount=[Number of times] :loop [Commands you want to repeat] set /a loopcount=loopcount-1 if %loopcount%==0 goto exitloop goto loop :exitloop 

Example: Say "Hello World!" 5 times:

@echo off set loopcount=5 :loop echo Hello World! set /a loopcount=loopcount-1 if %loopcount%==0 goto exitloop goto loop :exitloop pause 

This example will output:

Hello World! Hello World! Hello World! Hello World! Hello World! Press any key to continue . . . 

Comments

Popular posts from this blog

Are Regular VACUUM ANALYZE Still Recommended Under 9.1?

Can Feynman Diagrams Be Used To Represent Any Perturbation Theory?