Andrew Bullock
Andrew Bullock

Reputation: 37378

batch file for loop with spaces in dir name

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

Upvotes: 66

Views: 88125

Answers (4)

js2010
js2010

Reputation: 27423

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"

Upvotes: 0

Jan Zyka
Jan Zyka

Reputation: 17898

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

Upvotes: 111

thomspengler
thomspengler

Reputation: 71

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

Upvotes: 7

Jason
Jason

Reputation: 8640

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.

Upvotes: 37

Related Questions