繁体   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