windows 将文件内容读入数组的批处理脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3718788/
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
Batch script to read file contents into an array
提问by Picard
H guys, using a windows batch script I am looking to pass a run a command x number of times with a different argument each time, the arguments being parsed in from a file.
伙计们,使用 Windows 批处理脚本,我希望每次都使用不同的参数传递一个命令 x 次,这些参数是从文件中解析出来的。
For example have a textfile saying arg1 arg 2 arg3, the batch script would parse this and run
例如有一个文本文件说 arg1 arg 2 arg3,批处理脚本将解析它并运行
program.exe -arg1
program.exe -arg2
program.exe -arg3
I am thinking reading the file line by line into an array then doing a for each loop, but have no experience with windows scripting to do so
我正在考虑将文件逐行读入一个数组,然后为每个循环执行一次,但没有使用 Windows 脚本编写的经验
回答by Rudu
Alright, here we go... recall.bat. You always need to provide 1 argument - the executable to call each time. You also need to create an argument file: args.txt by default which should have one argument per line. If the argument has spaces or special characters it should be quote escaped.
好的,我们开始……recall.bat。您始终需要提供 1 个参数 - 每次调用的可执行文件。您还需要创建一个参数文件: args.txt 默认情况下,每行应该有一个参数。如果参数有空格或特殊字符,它应该被引号转义。
Source:recall.bat
来源:recall.bat
@echo off
setLocal EnableDelayedExpansion
::: recall.bat - Call an executable with a series of arguments
::: usage: recall $exec [$argfile]
::: exec - the executable to recall with arguments
::: argfile - the file that contains the arguments, if empty will
::: default to args.txt
::: argfile format:
::: One argument per line, quote-escaped if there's spaces/special chars
if "%~1"=="" findstr "^:::" "%~f0"&GOTO:EOF
set argfile=args.txt
:: Reset argfile if supplied.
if "%~2" neq "" set argfile="%~2"
:: Remove quotes
set argfile=!argfile:"=!
for /f "tokens=*" %%G in (%argfile%) do (
call %1 %%G
)
Example:
例子:
args.txt
args.txt
hello
world
"hello world"
Call:
称呼:
recall echo args.txt
Output:
输出:
hello
world
"hello world"
回答by Mark Wilkins
You should be able to use a for
loop. Assuming the file args.txt
contains the parameters, then this should work:
您应该能够使用for
循环。假设文件args.txt
包含参数,那么这应该可以工作:
for /f %a in (args.txt) do program.exe -%a
EditDepending on the command processor you are using, you may need to use two %
symbols in a row in the command if you run the above statement in a batch file. It is not necessary when using the very nice JP Softwarecommand prompt. I think, though, it is necessary with the default cmd.exe/command.com prompts.
编辑根据您使用的命令处理器,%
如果您在批处理文件中运行上述语句,您可能需要在命令中连续使用两个符号。使用非常好的 JP 软件命令提示符时不需要。不过,我认为,默认的 cmd.exe/command.com 提示是必要的。
for /f %%a in (args.txt) do program.exe -%%a