Cmd : not evaluating variables inside a loop
trying to make a .bat script, and need to get some st开发者_JAVA技巧rings working properly.
This is what I've got so far
@echo off
for /r %%i in (*.csv) do (
set str=%%i
set str=%str:csv=rar%
echo %%i
echo.%str%
)
Say I've got this running in C:\, and got 5 csv, 1.csv, 2.csv... 5.csv
First time I run it, I get output of:
C:\1.csv
C:\2.csv
C:\3.csv
C:\4.csv
C:\5.csv
The second time I get:
C:\1.csv
csv=rar
C:\2.csv
csv=rar
C:\3.csv
csv=rar
C:\4.csv
csv=rar
C:\5.csv
Then all subsequent calls I get:
C:\1.csv
rar=rar
C:\2.csv
rar=rar
C:\3.csv
rar=rar
C:\4.csv
rar=rar
C:\5.csv
When what I would be expecting to get is straight through:
C:\1.csv
C:\1.rar
C:\2.csv
C:\2.rar
C:\3.csv
C:\3.rar
C:\4.csv
C:\4.rar
C:\5.csv
C:\5.rar
So I remove the substitution:
@echo off
for /r %%i in (*.csv) do (
echo %%i
set str=%%i
echo.%str%
)
First run:
C:\1.csv
C:\2.csv
C:\3.csv
C:\4.csv
C:\5.csv
Second Run:
C:\1.csv
C:\5.csv
C:\2.csv
C:\5.csv
C:\3.csv
C:\5.csv
C:\4.csv
C:\5.csv
C:\5.csv
C:\5.csv
It's like it's not set the str variable until the last run of the loop, even though it's trying to echo out the variable, the line of which occurs after the setting, and then saved this for the next loop? Is there something I'm missing on the way it processess loops?
Thanks
You should use setlocal enabledelayedexpansion
. Actually, the content of %str:csv=rar%
is evaluated only once before the loop runs. So:
@echo off
setlocal enabledelayedexpansion
for /r %%I in (*.csv) do (
set str=%%i
set str=!str:csv=rar!
echo %%i
echo.!str!
)
endlocal
精彩评论