2011-03-18 40 views
2

我得到了1.txt2.txt在我的工作目錄中。我使用下面的批處理來列出所有文件。關於windows批處理文件的奇怪問題

批次是這樣的:

@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 

感謝。

+0

謝謝,修復它。 – smwikipedia 2011-03-18 08:05:52

回答

6

你需要把:

@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%將替換爲在循環開始之前它保留的值。使用延遲擴展會推遲評估,直到執行實際行。


有各種精彩的Windows腳本技巧上的Rob van der Woude's site,含有相當多的Windows下做事的不同工具的不同方式。

+0

@smwikipedia:這同樣適用於其他需要使用括號括起來的命令塊的情況,如'if ...(...)else(...)'。 – 2011-03-18 07:42:04

+0

是否有任何官方文件對照!變量之間的差異!和%變量%符號? – smwikipedia 2011-03-18 09:01:59

+0

是的,我找到了一個很好的參考:http://ss64.com/nt/setlocal.html – smwikipedia 2011-03-18 09:15:49

1

在這種特殊情況下,你可以得到正確的輸出,如果你呼應file_variable這樣的:

CALL ECHO file_variable=%%file_variable%% 

這種方法不夠靈活,或許比@paxdiablo的回答中描述的少了一個高性能的。這可能只是一種延遲變量擴展而不需要啓用特殊語法的快捷方法。