【问题标题】:Batch script to read file contents into an array将文件内容读入数组的批处理脚本
【发布时间】:2010-09-15 14:47:06
【问题描述】:

伙计们,我希望使用 Windows 批处理脚本来传递一个运行命令 x 次,每次使用不同的参数,这些参数是从文件中解析的。

例如有一个文本文件说 arg1 arg 2 arg3,批处理脚本会解析并运行

program.exe -arg1
program.exe -arg2
program.exe -arg3

我正在考虑将文件逐行读取到一个数组中,然后为每个循环执行一次,但没有使用 Windows 脚本编写的经验

【问题讨论】:

    标签: windows batch-file


    【解决方案1】:

    好的,我们开始吧……recall.bat。您总是需要提供 1 个参数 - 每次调用的可执行文件。您还需要创建一个参数文件:默认情况下,args.txt 每行应该有一个参数。如果参数包含空格或特殊字符,则应使用引号转义。

    来源: 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
    )
    

    例子:

    args.txt

    hello
    world
    "hello world"
    

    呼叫:

    recall echo args.txt
    

    输出:

    hello
    world
    "hello world"
    

    【讨论】:

      【解决方案2】:

      您应该能够使用for 循环。假设文件args.txt 包含参数,那么这应该可以工作:

      for /f %a in (args.txt) do program.exe -%a
      

      编辑根据您使用的命令处理器,如果您在批处理文件中运行上述语句,您可能需要在命令中连续使用两个% 符号。使用very nice JP Software 命令提示符时不需要。不过我认为,有必要使用默认的 cmd.exe/command.com 提示符。

      for /f %%a in (args.txt) do program.exe -%%a
      

      【讨论】:

        猜你喜欢
        • 2011-03-05
        • 2015-11-02
        • 2013-07-30
        • 2015-05-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-23
        • 1970-01-01
        相关资源
        最近更新 更多