%X在这个时候意外。批处理脚本 [英] %x was unexpected at this time. batch script
问题描述
关闭@echo
FOR / F令牌= 1,2 = delims,%%倍In(my.csv)做(
如果%M%LSS %% x设定M = %%点¯x
)
呼应最大X值=%M%
有时它工作正常,有时失败,以下错误:
%X在这个时候意外。
的问题是,你使用%M%
在的
循环。当环路被读取(之前的任何迭代在所有)此被评估。换言之,整个循环,直到并包括右括号,被读出和执行之前进行评价。因此,%M%
将永远是它的初始值,不管你实际的循环内将其设置为
一个例子应该有希望说明这一点:
设置VAL = 7
对于%%我在(1)做(
设置VAL = 99
回声%VAL%
)
回声%VAL%
这导致了意想不到的(一些):
7
99
仅仅是因为%VAL%
第一回波语句间preTED(即整个为
循环PTED间$ p $)它的任何运行之前。
您需要的东西沿着延迟扩展,这将迫使 M
的值设置为第一个 %% X
不管。使用 SETLOCAL
命令和 M!!
而不是%M%
将推迟 M
评估每次执行行时间,直到
此外,设置 M
最初不了了之,并迫使它是 %% X
时,它的是的什么都不会保证的第一个值%% X
被装入 M
。
关闭@echo
SETLOCAL ENABLEEXTENSIONS enabledelayedexpansion
设定M =
FOR / F令牌= 1,2 = delims,%%倍In(my.csv)做(
如果M!! ==设定M = %%点¯x
如果M!! LSS %% X设置M = %%点¯x
)
回声最大X值= M!!
ENDLOCAL
使用上述code本 my.csv
文件:
1,
2,B
10,C
3,D
结果的输出:
最大X值= 10
如预期,或者在另一个注释示例数据:
422,34
464,55
455,65
421,88
您可以:
最大X值= 464
@echo off
for /f "tokens=1,2 delims=," %%x in (my.csv) do (
if %M% LSS %%x set M=%%x
)
echo Max X Value= %M%
Sometimes it works fine, sometimes it fails with following error:
%x was unexpected at this time.
The problem is that you're using %m%
inside a for
loop. This is evaluated when the loop is read (before any iterations at all). In other words, the entire loop, up to and including the closing parenthesis, is read and evaluated before executing. So %m%
will always be it's initial value no matter what you actually set it to within the loop.
An example should hopefully illustrate this:
set val=7
for %%i in (1) do (
set val=99
echo %val%
)
echo %val%
which results in the unexpected (to some):
7
99
simply because the %val%
in the first echo statement is interpreted (i.e., the entire for
loop is interpreted) before any of it is run.
You need delayed expansion along with something that will force the value of m
to be set to the first %%x
regardless. Using the setlocal
command and !m!
instead of %m%
will delay evaluation of m
until each time the line is executed.
In addition, setting m
initially to nothing and forcing it to be %%x
when it is nothing will ensure the first value of %%x
is loaded into m
.
@echo off
setlocal enableextensions enabledelayedexpansion
set m=
for /f "tokens=1,2 delims=," %%x in (my.csv) do (
if "!m!" == "" set m=%%x
if !m! lss %%x set m=%%x
)
echo Max X Value = !m!
endlocal
Using the above code with this my.csv
file:
1,a
2,b
10,c
3,d
results in the output of:
Max X Value = 10
as expected or, for your sample data in another comment:
422,34
464,55
455,65
421,88
you get:
Max X Value = 464
这篇关于%X在这个时候意外。批处理脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!