5

在我的 Windows 批处理文件中,我有一些带有不同数量字符串的变量。例如:

set string="-start" "-end someOption" 

我通过以下方式计算字符串的数量:

Set count=0
For %%j in (%string%) Do Set /A count+=1
echo.Total count: %count%

输出将是:

Total count: 2

现在,我想启动应用程序的次数与变量中有字符串一样多,并且我想为应用程序提供当前字符串作为参数。我试过这个:

 FOR /L %%H IN (1,1,%COUNT%) DO ( 

    echo %%H
        FOR /F "tokens=%%H " %%I IN ("%string%") Do (
            echo %%I
            rem java -jar app.jar %%I
        )
    )

但不幸的是,这不起作用:这就是输出:

当前字符串的数量:1 "%H "" kann syntaktisch an dieser Stelle nicht verarbeitet werden. (%H "" 在这个地方不能在语法上使用) 当前字符串的数量:2 "%H "" kann syntaktisch an dieser Stelle nicht verarbeitet werden。

如何循环遍历变量“字符串”中的两个字符串?

4

2 回答 2

6

您不能在 的选项字段中使用 FOR 参数或延迟扩展变量FOR/F
但是您可以创建一个函数并在那里使用百分比扩展。

拆分是 delim 字符的效果,它是每个默认的空格和制表符,它们也适用于带引号的参数。
因此,我将您的分隔符更改为分号,然后就可以了。

set string="-start";"-end someOption" 
set count=0
For %%j in (%string%) Do Set /A count+=1
echo.Total count: %count%

FOR /L %%H IN (1,1,%COUNT%) DO ( 

    echo %%H
    call :myFunc %%H
)
exit /b
:myFunc
FOR /F "tokens=%1 delims=;" %%I IN ("%string%") Do (
  echo %%~I
  rem java -jar app.jar %%I
)
exit /b
于 2012-08-22T12:13:59.437 回答
0

Ok I will try to make it more clearly.

The answer above helped me just a bit.

As I showed at the beginning of my question I have the following variable:

set string="-start" "-end someOption" 

I wanted to loop through this variable so that at the end I have two complete parameters: first one:

"-start"

second one:

"-end someOption"

But after calling the function the echos are:

"-start" 

(this is correct) and

"-end

/this is wrong because he slits the string at the whitespace.

But at the end for starting my application I need two correct parameters. They should look like this: first parameter:

-start

and second parameter with one option:

-end someoption

So I need to eliminate the quotation marks and the second paramert must not be splitted at the whitemark.

于 2012-08-22T13:35:19.430 回答