我是Windows脚本新手(使用bash多年后)。我有一个问题,了解Windows批处理文件执行循环的方式。
我有三个嵌套的for循环,每个内部循环的变量取决于它所在的循环变量:
for %%i in (0,1,%maxnum%) do (
for %%j in (0,1,%%i) do (
for %%k in (0,1,%%j) do (
echo L%%i_M%%j_N%%k ) ) )
如果我设置" maxnum"等于2,这个循环应该打印出来:
L0_M0_N0
L1_M0_N0
L1_M1_N0
L1_M1_N1
L2_M0_N0
L2_M1_N0
L2_M1_N1
L2_M2_N0
L2_M2_N1
L2_M2_N2
并且不超过这10个字符串。但是,我注意到,如果例如%% i = 0,则第二个for循环遍历(0,1,0)中的%% j并执行其内容,不仅对于%% j = 0而且对于%% j = 1,这太刺激了!
我通过在echo之前添加if语句来限制输出:
for %%i in (0,1,%maxnum%) do (
for %%j in (0,1,%%i) do (
for %%k in (0,1,%%j) do (
if %%k LEQ %%j (
if %%j LEQ %%i (
echo L%%i_M%%j_N%%k ) ) ) ) )
然后打印出来:
L0_M0_N0
L0_M0_N0
L0_M0_N0
L0_M0_N0
L1_M0_N0
L1_M0_N0
L1_M1_N0
L1_M1_N1
L1_M1_N1
L1_M1_N0
L1_M1_N1
L1_M1_N1
L2_M0_N0
L2_M0_N0
L2_M1_N0
L2_M1_N1
L2_M1_N1
L2_M2_N0
L2_M2_N1
L2_M2_N2
,对于字符串LX_MY_NZ,确实Z <= Y <= X但是重复了一些字符串,这对于我想要使用此代码的问题是有问题的。
当for循环的起始值和结束值相同时,是否有办法绕过这种情况?或者我只是不了解如何在Windows批处理文件中使用for循环?
非常感谢您的意见!谢谢!
答案 0 :(得分:0)
您需要将/L
参数添加到for
语句中。
FOR /L %variable IN (start,step,end) DO command [command-parameters]
The set is a sequence of numbers from start to end, by step amount.
So (1,1,5) would generate the sequence 1 2 3 4 5 and (5,-1,1) would
generate the sequence (5 4 3 2 1)