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

Categories

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

batch file - Cmd : not evaluating variables inside a loop

trying to make a .bat script, and need to get some strings 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

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...