簡體   English   中英

將批處理目錄輸出保存到變量

[英]save batch dir output to a variable

我有一個部分文件名。 我正在使用通配符執行dir以獲取完整的文件名。 我正在尋找一種檢查文件是否存在然后將完整文件名保存到變量的方法。

到目前為止,這是行不通的。

    if exist file_00001_%Yr%%Mth%0%newDate%*.pcap (
        echo file is here
        FOR /F %i IN ('dir file_00001_%Yr%%Mth%0%newDate%*.pcap') DO SET newTestFile=%i
        echo %newTestFile%
    ) else (
        echo file is not here
    )

我的代碼確實驗證了該文件確實存在,但是一旦獲得文件名,我想將其保存到一個變量中,以便能夠剝離文件名中隨機創建的部分。

確保您需要延遲擴展,並且需要使用dir / b去除不必要的數據,並為令牌增加%

 setlocal enableDelayedExpansion
 if exist file_00001_%Yr%%Mth%0%newDate%*.pcap (
    echo file is here
    FOR /F %%i IN ('dir /b /a-d file_00001_%Yr%%Mth%0%newDate%*.pcap') DO SET "newTestFile=%%~i"
    echo !newTestFile!
) else (
    echo file is not here
)

或者您可以優化代碼

 setlocal enableDelayedExpansion
 if exist file_00001_%Yr%%Mth%0%newDate%*.pcap (
    echo file is here
    FOR  %%i IN ("file_00001_%Yr%%Mth%0%newDate%*.pcap") DO SET "newTestFile=%%i"
    echo !newTestFile!
) else (
    echo file is not here
)

我不明白為什么人們使用for /F ... in ('dir /b ...來搜索文件時,平原for命令設計(超過25年前)用於此目的:

set "newTestFile="
for %%i in (file_00001_%Yr%%Mth%0%newDate%*.pcap) do set newTestFile=%%i
if defined newTestFile (
   echo file is here: %newTestFile%
) else (
   echo file is not here
)

順便說一句,您的代碼中的錯誤是%i FOR參數必須具有雙百分號: %%idir命令必須包含/b開關。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM