开发者

how to do loop in Batch?

I want to create something like this

dup.bat infile outfile times

example usage would be

dup.bat a.txt a5.txt 5

at it would create file a5.txt that has the content of a.t开发者_如何学Pythonxt repeated 5 times

however I do not know how to do for loop in batch, how to do it?


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 the input file and repeat it, you could use MORE with redirection to append the contents of the input file to the output file. Note 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%
)


For command line args

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

To do a simple for loop, read in from the input file, and write 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 file, you could also do it via command line:

dup.bat a.txt 5 > a5.txt


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 (times=5) Start subroutine Beginning If your counter doesn't equal 0, read a.txt and APPEND its contents to a5.txt, then decrement your counter by 1. This will repeat five times until your counter equals 0, then it will cleanup your variable and end the script. SET ENABLEDELAYEDEXPANSION is important to increment variables within loops.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜