windows 如何在批处理中进行循环?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5598955/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to do loop in Batch?
提问by IAdapter
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.txt repeated 5 times
它将创建文件 a5.txt,其中 a.txt 的内容重复 5 次
however I do not know how to do for loop in batch, how to do it?
但是我不知道如何批量进行for循环,该怎么做?
回答by Jeff Mercado
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.
然后要获取输入文件并重复它,您可以使用MORE
重定向将输入文件的内容附加到输出文件。请注意,这假定这些是文本文件。
@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%
)
回答by Gavin Miller
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 循环,请从input
文件中读取并写入output
文件:
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
回答by Mechaflash
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.
设置您的计数器 (times=5) Start subroutine Beginning 如果您的计数器不等于 0,则读取 a.txt 并将其内容附加到 a5.txt,然后将您的计数器减 1。这将重复五次,直到您的计数器等于 0 ,然后它将清理您的变量并结束脚本。SET ENABLEDELAYEDEXPANSION 对于增加循环内的变量很重要。