【问题标题】:Batch - Write output of DIR to a variable批处理 - 将 DIR 的输出写入变量
【发布时间】:2018-05-07 03:01:56
【问题描述】:

我必须将DIR 的输出存储在一个变量中。

这是之前问过的,例如hereherehere

他们都提供了一个或多或少类似于我现在使用的答案:

%= Find the *.sln file and write its path to the file temp.temp =%
DIR /s/b *.sln > temp.temp

%= Read out the content of temp.temp again to a variable =%
SET /p texte=< temp.temp

%= Remove the temp.temp file =%
DEL temp.temp

%= Get only the filename without path =%
FOR %%A IN ("%texte%") DO (
    SET Name=%%~nxA
)

但就我而言,我确信DIR /s/b *.sln 的输出总是单行。对我来说,不得不这样做看起来有点难看
a) 将输出存储在外部文件中,然后
b) 在它上面运行一个FOR 循环,虽然我已经知道它只有一行。

是否有任何直接/更简单的方法可以做到这一点?

【问题讨论】:

    标签: windows batch-file output


    【解决方案1】:
    for /f "delims=" %%a in ('dir /s /b *.sln') do set "name=%%a"
    

    确实是最有效的方法(您可以直接处理命令的输出,不需要临时文件)。
    %name% 将包含文件的完整限定文件名(或最后一个文件,如果有多个)

    【讨论】:

    • delims 到底是我称之为texte 的变量,对吗?而且我想我仍然可以使用name=%%~nxA 来获取文件名?
    • delims= 将 delims 设置为“无分隔符”。默认情况下,for /f 使用tokens=1 和空格、逗号、制表符分隔符进行处理。如果你把它留给标准,它只会给你输出的第一个字:尝试(直接在命令行上)for /f %a in ("hello world") do @echo %a vs for /f "delims=" %a in ("hello world") do @echo %a
    • 是的:? name=%%~nxA 当然是可能的(注意:for 变量区分大小写:%%a 不是 %%A
    • @RamonRoyo 既不是%%a 也不是for,它去掉了感叹号。是延迟扩张。之前关掉它 (setlocal disabledelayedexpansion)
    • @afifi:要引用的内容:in ('dir /b /s "*%yy%%mm%%dd%_%bn%_P_*"') doIF EXIST "%name%" GOTO
    猜你喜欢
    • 2014-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多