批处理 - 将DIR命令的输出写入变量

13

我需要将DIR的输出存储到一个变量中。

这个问题之前也被问过,例如这里这里这里

它们都提供了与我现在使用的差不多的答案:

%= 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 的输出始终是单行的。对我来说,将输出存储在外部文件中并运行一个FOR循环虽然已经知道它只有一行,看起来有点丑陋。

有没有更简单直接的方法来做到这一点?

1个回答

17
for /f "delims=" %%a in ('dir /s /b *.sln') do set "name=%%a"

实际上,indeed是最有效的方法(您可以直接处理命令的输出,无需使用临时文件)。 %name%将包含您的文件的完整限定文件名(如果有多个文件,则为这些文件中的最后一个)。


delims 是我称之为 texte 的变量,对吗?我猜我仍然可以使用 name=%%~nxA 来仅获取文件名? - derHugo
1
delims= sets delims to "no delimiter". By default, for /f is processed with tokens=1 and delimiters of space, comma, tab. If you leave it to standards, it will give you the very first word of the output only: Try (directly on command line) for /f %a in ("hello world") do @echo %a vs for /f "delims=" %a in ("hello world") do @echo %a - Stephan
1
@RamonRoyo 这不是 %%afor 删除感叹号。这是延迟执行。在此之前关闭它 (setlocal disabledelayedexpansion)。 - Stephan
@Stephan,我也在我的脚本中使用这个,但是当文件夹名称有空格时,它无法找到文件夹内的文件。例如,文件夹名称为E:\parent\new folder\new.txt。有什么解决办法可以帮忙吗? - afifi
1
@afifi:需要引用的内容:“in ('dir /b /s "%yy%%mm%%dd%_%bn%P"') do”和“IF EXIST "%name%" GOTO”。 - Stephan
显示剩余6条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接