Batch - Write output of DIR to a variable

徘徊边缘 提交于 2019-12-01 20:34:59

问题


I have to store the ouput of DIR in a variable.

This was asked before e.g. here or here or here.

They all provide an answer more or less similar to what I'm using right now:

%= 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
)

But in my case I'm sure that the ouput of DIR /s/b *.sln will allways be a one-liner. To me it looks a bit ugly to have to
a) store the ouput in an external file and
b) run a FOR loop over it though I already know it will only have one line.

Is there any direct/simpler way to do this?


回答1:


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

indeed is the most efficient method (you can process the output of a command directly, no need for a temporary file).
%name% will contain the full qualified file name of your file (or the last of the files, if there are more than one)



来源:https://stackoverflow.com/questions/47450531/batch-write-output-of-dir-to-a-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!