奇怪的问题关于windows批处理文件 [英] Strange question about windows batch file
问题描述
我在我的工作目录中有 1.txt 和 2.txt 。我使用以下批处理列出所有文件。
批次是这样的:
@echo off
for / ftokens = *%% a in('dir * .txt / b')do(
echo --------- ------
set file_variable = %% a
echo file_variable =%file_variable%
echo filename = %% a
)
结果如下:
--------------
file_variable = 2.txt< ---------------为什么它不是1.txt这里?
filename = 1.txt
---------------
file_variable = 2.txt
filename = 2txt
谢谢。
解决方案您需要输入:
@setlocal enableextensions enabledelayedexpansion
在文件顶部
endlocal
延迟扩展替换字符。
@setlocal enableextensions enabledelayedexpansion
@echo off
for / ftokens = *%% a in('dir * .txt / b')do(
echo ---------------
set file_variable = %% a
echo file_variable =!file_variable!
echo filename = %% a
)
endlocal
C:\Documents和Settings \Pax\ My Documents> ; qq.cmd
---------------
file_variable = 1.txt
filename = 1.txt
------ ---------
file_variable = 2.txt
filename = 2.txt
b $ b
没有延迟扩展的是,在运行之前,正在评估
循环的整个
循环。这包括替换,以便循环开始之前,
%file_variable%
将替换为它保存的值。
有各种精彩的Windows脚本技巧, Rob van der Woude的网站,包含使用各种工具在Windows下执行操作的很多不同方法。 p>
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.
解决方案You need to put:
@setlocal enableextensions enabledelayedexpansion
at the top of your file and
endlocal
at the end.
Then you need to use the delayed expansion substitution characters.
@setlocal enableextensions enabledelayedexpansion @echo off for /f "tokens=*" %%a in ('dir *.txt /b') do ( echo --------------- set file_variable=%%a echo file_variable=!file_variable! echo filename=%%a ) endlocal C:\Documents and Settings\Pax\My Documents> qq.cmd --------------- file_variable=1.txt filename=1.txt --------------- file_variable=2.txt filename=2.txt
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.
这篇关于奇怪的问题关于windows批处理文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!