batch file for loop with spaces in dir name

WindowsBatch FileCmd

Windows Problem Overview


How do I modify this:

for /f %%a IN ('dir /b /s build\release\*.dll') do echo "%%a"

to work when the path contains spaces?

For example, if this is run from

c:\my folder with spaces

it will echo:

c:\my

Thanks

Windows Solutions


Solution 1 - Windows

You need to use:

for /f "delims=" %%a IN ('dir /b /s build\release\*.dll') do echo "%%a"

This overrides the default delimiters which are TAB and SPACE

Solution 2 - Windows

I got around this by prepending "type" and putting double quotes surrounding the path in the IN clause

FOR /F %%A IN ('type "c:\A Path With Spaces\A File.txt"') DO (
    ECHO %%A
)

This article gave me the idea to use "type" in the IN clause.

Solution 3 - Windows

If you don't want to deal with "quotes" you can use the "s" switch in %~dpnx[]... this will output the short filenames that are easy to work with.

from the Command line...

for /f "delims=" %f IN ('dir /b /s "C:\Program Files\*.dll"') do echo %~sdpnxf

inside a .CMD/.BAT file you need to "escape" the [%] e.g., double-up [%%]

for /f "delims=" %%f IN ('dir /b /s "C:\Program Files\*.dll"') do echo %%~sdpnxf

Solution 4 - Windows

The problem is there's a wildcard in the string that gets interpreted as a filename. You also need double quotes for a string with spaces. I'm not sure if there's a way to escape the wildcard.

for %a IN ("dir /b /s build\release\.dll") do echo %a
"dir /b /s build\release\.dll"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAndrew BullockView Question on Stackoverflow
Solution 1 - WindowsJan ZykaView Answer on Stackoverflow
Solution 2 - WindowsJasonView Answer on Stackoverflow
Solution 3 - WindowsthomspenglerView Answer on Stackoverflow
Solution 4 - Windowsjs2010View Answer on Stackoverflow