Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

%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.
like image 711
stack Avatar asked Feb 03 '10 07:02

stack


2 Answers

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
like image 105
paxdiablo Avatar answered Oct 03 '22 21:10

paxdiablo


There's no environment variable named M set, so when this line is interpreted:

if %M% LSS %%x set M=%%x

After the 1st round of replacements, it looks to the interpreter something like

if LSS %x set M=%x

To avoid the problems that paxdiablo mentions about %M%being expanded only when the loop is first you can use the delayed expansion feature that he discusses, or move testing and setting M to a subroutine that is called from the loop but exists outside the loop so it gets interpreted (and expanded) on each call:

@echo off
set M=
for /f "tokens=1,2 delims=," %%x in (my.csv) do (
    call :setmax %%x
)
echo Max X Value= %M%
goto :eof

:setmax
if "%M%" == "" set M=%1
if %M% LSS %1 set M=%1
goto :eof
like image 30
Michael Burr Avatar answered Oct 03 '22 22:10

Michael Burr