Batch file Loop with spaces

2019-09-05 13:43发布

问题:

I have this tiny annoying thing that is driving me nuts. I need to loop through a directory and move files contained within a subdir to another location.

This works fine for folders that don't contain any spaces, but I have some directories that contain spaces, which do not work. I've tried adding some "" around the file location, but that doesn't work either.

This is what I have:

for /f "usebackq" %%m in (`dir /b D:\adir\dir with spaces`) do (
    MOVE /Y "D:\adir\dir with spaces\%%m\*.*" "D:\bdir\dir with spaces"
    RD /q D:\adir\dir with spaces\%%m
) 

回答1:

The first thing I would do is put quotes inside the parentheses and in the RD command:

for /f "usebackq" %%m in (`dir /b "D:\adir\dir with spaces"`) do (
    MOVE /Y "D:\adir\dir with spaces\%%m\*.*" "D:\bdir\dir with spaces"
    RD /q "D:\adir\dir with spaces\%%m"

Then I would see how it goes...

This (with quotes) "works for me":

@echo off
for /f "usebackq" %%m in (`dir /b "z:\dir with spaces"`) do (
    dir "z:\dir with spaces\%%m"
)

This (without the quotes) does NOT work:

@echo off
for /f "usebackq" %%m in (`dir /b z:\dir with spaces`) do (
    dir z:\dir with spaces\%%m
)


回答2:

for /f "delims=" %%m in ('dir /b /ad "D:\adir\dir with spaces"') do (
    MOVE "D:\adir\dir with spaces\%%~m\*" "D:\bdir\dir with spaces"
    RD "D:\adir\dir with spaces\%%~m"