Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

@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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...