如何运行带有两个变量的命令更改并增加输出文件名

时间:2014-09-25 17:39:07

标签: windows loops batch-file scripting cmd

如何运行包含两个变量的命令?一个是递增的,另一个是由某个路径确定的变量。

问题是该命令不允许在一个命令中加载多个路径。 每次检查我有10个以上的文件夹,我必须为每个命令生成一个增加的唯一文件名,因为它不会被下一个命令覆盖。

这里的示例可能更容易理解,但它不起作用,因为它没有增加,因此它会覆盖以前的文件。

    @echo off

    SET "basename=file"
    SET /a outname=0

    :genloop
    SET /a outname+=1

    IF EXIST "%basename%-%outname%.csv" GOTO genloop
    SET "outname=%basename%-%outname%.csv"

    command.exe /out %outname% /LoadDirectory "C:\Dir-EXAMPLE-1"
    command.exe /out %outname% /LoadDirectory "C:\Dir-EXAMPLE-ABC"
    command.exe /out %outname% /LoadDirectory "C:\Dir-EXAMPLE-XYZ"
    command.exe /out %outname% /LoadDirectory "C:\Dir-EXAMPLE-ETC"

此问题与此How to create a unique output filename for Windows Script?

有关

我怎样才能以简单而优雅的方式做到这一点?

提前致谢。

修改

感谢@MC ND& @ths,这两种解决方案都能很好地工作,特别是因为你非常乐于助人和专注。我不知道是否有可能批准这两个解决方案,但如果我必须做出选择,我会选择第二个选项,因为它最接近关于这两个变量的问题并且评论很好。 我不会忘记@Magoo,因为我很感激他的鼓励,谢谢。

PS:鉴于我的问题,脚本是完美的,但也许在不久的将来,我会问一个与之相关的新问题,使其在某些情况下更加复杂。 (在脚本解释器的可能性中)

PPS:如果我的问题不是很清楚简洁,对不起其他人。随意修改内容和标签,使其更易于理解。

2 个答案:

答案 0 :(得分:1)

你基本上已经拥有了大部分必需的组件,我将添加子例程的概念:

@echo off

SET "basename=file"
SET /a outnum=0

call :genloop
command.exe /out %outname% /LoadDirectory "C:\Dir-EXAMPLE-1"
call :genloop
command.exe /out %outname% /LoadDirectory "C:\Dir-EXAMPLE-ABC"
call :genloop
command.exe /out %outname% /LoadDirectory "C:\Dir-EXAMPLE-XYZ"
call :genloop
command.exe /out %outname% /LoadDirectory "C:\Dir-EXAMPLE-ETC"

goto :eof

:genloop
SET /a outnum+=1

IF EXIST "%basename%-%outnum%.csv" Call :genloop
SET "outname=%basename%-%outnum%.csv"
goto :eof

答案 1 :(得分:1)

@echo off
    setlocal enableextensions disabledelayedexpansion

    rem configure script 
    set "basename=file"
    set "counter=1000000"
    set folders="C:\Dir-EXAMPLE-1" "C:\Dir-EXAMPLE-ABC" "C:\Dir-EXAMPLE-XYZ" "C:\Dir-EXAMPLE-ETC" 

    rem Search the last file in the sequence
    for /f "tokens=2 delims=-.0" %%a in ('
        dir /b /a-d /o-n "%basename%-??????.csv" 2^>nul
    ') do set /a "counter=1000000+%%a" & goto done
    :done

    rem Iterate the folders list
    for %%a in (%folders%) do (

        rem increment file counter
        set /a "counter+=1"

        rem get access to the counter with delayed expansion, but
        rem to prevent problems with possible exclamations in paths
        rem disable delayed expansion before executing the commands
        rem so, we need the `for` to store the counter data into %%b

        setlocal enabledelayedexpansion
        for %%b in (!counter:~-6!) do (
            endlocal 

            rem just for testing, generate the output file
            rem remove this line in real code
            type nul >"%basename%-%%b.csv" 

            rem execute the command - command is only echoed to console
            rem if the output is correct, remove the echo
            echo command.exe /out "%basename%-%%b.csv" /LoadDirectory "%%~a"
        )
    )