[ACCEPTED]-how to do loop in Batch?-dos

Accepted answer
Score: 12

You can do the loop like this:

SET infile=%1
SET outfile=%2
SET times=%3

FOR /L %%i IN (1,1,%times%) DO (
    REM do what you need here
    ECHO %infile%
    ECHO %outfile%
)

Then to take 4 the input file and repeat it, you could 3 use MORE with redirection to append the contents 2 of the input file to the output file. Note 1 this assumes these are text files.

@ECHO off
SET infile=%1
SET outfile=%2
SET times=%3

IF EXIST %outfile% DEL %outfile%
FOR /L %%i IN (1,1,%times%) DO (
    MORE %infile% >> %outfile%
)
Score: 3

For command line args

set input=%1
set output=%2
set times=%3

To do a simple for 3 loop, read in from the input file, and write 2 to the output file:

FOR /L %%i IN (1,1,%times%) DO (
    FOR /F %%j IN (%input%) DO (
        @echo %%j >> %output%
    )      
)

Instead of taking in an output 1 file, you could also do it via command line:

dup.bat a.txt 5 > a5.txt
Score: 0

sigh

Compact Design:

SETLOCAL ENABLEDELAYEDEXPANSION
SET times=5
:Beginning
IF %times% NEQ 0 (TYPE a.txt>>a5.txt & SET /a times=%times%-1 & GOTO Beginning) ELSE ( ENDLOCAL & set times= & GOTO:eof)

Easy Reading:

SETLOCAL ENABLEDELAYEDEXPANSION
SET times=5
:Beginning
IF %times% NEQ 0 (
TYPE a.txt>>a5.txt
SET /a times=%times%-1
GOTO Beginning
) ELSE (
ENDLOCAL
set times=
GOTO:eof
)

Set your counter 9 (times=5) Start subroutine Beginning If 8 your counter doesn't equal 0, read a.txt 7 and APPEND its contents to a5.txt, then 6 decrement your counter by 1. This will 5 repeat five times until your counter equals 4 0, then it will cleanup your variable and 3 end the script. SET ENABLEDELAYEDEXPANSION 2 is important to increment variables within 1 loops.

More Related questions