Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
903 views
in Technique[技术] by (71.8m points)

windows - %x was unexpected at this time. batch script

@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.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...