问题描述
正在尝试制作 .bat 脚本,并且需要让一些字符串正常工作.
trying to make a .bat script, and need to get some strings working properly.
这是我目前得到的
@echo off
for /r %%i in (*.csv) do (
set str=%%i
set str=%str:csv=rar%
echo %%i
echo.%str%
)
假设我在 C: 中运行了它,并且得到了 5 个 csv、1.csv、2.csv... 5.csv
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
我第二次得到:
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
所以我删除了替换:
@echo off
for /r %%i in (*.csv) do (
echo %%i
set str=%%i
echo.%str%
)
第一次运行:
C:1.csv
C:2.csv
C:3.csv
C:4.csv
C:5.csv
第二次运行:
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
这就像直到循环的最后一次运行才设置 str 变量,即使它试图回显变量,在设置之后发生的行,然后将其保存以供下一个循环使用?我在处理循环的过程中是否遗漏了什么?
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?
谢谢
推荐答案
你应该使用 setlocal enabledelayedexpansion
.实际上,%str:csv=rar%
的内容在循环运行前只计算一次.所以:
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
这篇关于Cmd:不在循环内评估变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!