gpt4 book ai didi

scripting - 关于windows批处理文件的奇怪问题

转载 作者:行者123 更新时间:2023-12-04 21:54:21 25 4
gpt4 key购买 nike

我的工作目录中有 1.txt2.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

谢谢。

最佳答案

你需要输入:

@setlocal enableextensions enabledelayedexpansion

在你的文件的顶部和

endlocal

最后。

那么你需要使用延迟扩展替换字符。

@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

在没有延迟扩展的情况下,您看到的是整个 for 循环在运行之前被评估。这包括替换,因此 %file_variable% 将替换为它在循环开始之前所持有的值。使用延迟扩展将评估推迟到执行实际行时。


Rob van der Woude's site 提供了各种精彩的 Windows 脚本技巧。 ,包含在 Windows 下使用各种工具执行操作的许多不同方法。

关于scripting - 关于windows批处理文件的奇怪问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5349153/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com