关于windows批处理文件的奇怪问题
我的工作目录中有 1.txt 和 2.txt 。我使用以下批处理列出所有文件。
批次是这样的:
@echo off
for /f "tokens=*" %%a in ('dir *.txt /b') do (
echo ---------------
set file_variable=%%a
echo file_variable=%file_variable%
echo filename=%%a
)
结果如下:
---------------
file_variable=2.txt <---------------why it is not 1.txt here??
filename=1.txt
---------------
file_variable=2.txt
filename=2.txt
谢谢。
I got 1.txt and 2.txt in my working directory. I use the following batch to list all the files.
The batch is this:
@echo off
for /f "tokens=*" %%a in ('dir *.txt /b') do (
echo ---------------
set file_variable=%%a
echo file_variable=%file_variable%
echo filename=%%a
)
The result is below:
---------------
file_variable=2.txt <---------------why it is not 1.txt here??
filename=1.txt
---------------
file_variable=2.txt
filename=2.txt
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要将:
放在文件的顶部和
末尾。
那么就需要使用延迟扩展替换字符。
在没有延迟扩展的情况下,您所看到的是整个
for
循环在运行之前进行评估。这包括替换,以便%file_variable%
将被替换为循环开始之前保存的值。使用延迟扩展可以推迟评估,直到执行实际的行。Rob van der Woude 的网站 上有各种精彩的 Windows 脚本技巧,包含很多不同的方法使用各种工具在 Windows 下做事。
You need to put:
at the top of your file and
at the end.
Then you need to use the delayed expansion substitution characters.
What you're seeing without delayed expansion is that the entire
for
loop is being evaluated before running. That includes the substitution, so that%file_variable%
will be replaced with the value it held before the loop started. Using delayed expansion defers the evaluation until the actual line is executed.There are all sorts of wonderful Windows scripting tricks over at Rob van der Woude's site, containing quite a lot of different ways of doing things under Windows with various tools.
在这种特殊情况下,如果您像这样 ECHOed
file_variable
,您可以获得正确的输出:这种方法比 @paxdiablo 的答案。这可能只是延迟变量扩展的一种快速而肮脏的方法,而不需要为此启用特殊语法。
In this particular case you could get the correct output if you ECHOed
file_variable
like this:This approach is less flexible and probably less performant than the one described in @paxdiablo's answer. It's probably just a quick-and-dirty method of delaying the expansion of a variable without the need to enable the special syntax for that.