Spaces folder names in FOR loop

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
rscanny
Posts: 2
Joined: 12 Aug 2021 03:40

Spaces folder names in FOR loop

#1 Post by rscanny » 12 Aug 2021 03:50

I have a script that scans a directory and deletes any files that are listed in a text file. The script works great except for when it encounters a space in a folder name. I've tried using " " to stop the error occurring but to no avail. I've tried using " " in the variables set at the start of the script and also in the FOR loop itself, neither seems to make any difference! Can anyone give me some guidance please!

Code: Select all

set bat_location=%cd%
set del_name=files_to_delete.txt
set "remove=%bat_location%\%del_name%"
.
.
.
for /f "delims=" %%f in (%remove%) do del /Q "%%f" 2>NUL


kwsiebert
Posts: 42
Joined: 20 Jan 2016 15:46

Re: Spaces folder names in FOR loop

#2 Post by kwsiebert » 12 Aug 2021 09:04

Turn echo on, or replace the del command with echo, to see what exactly is different between the lines that work and the ones that don't. That should give a clue as to what needs to be changed.

ShadowThief
Expert
Posts: 1160
Joined: 06 Sep 2013 21:28
Location: Virginia, United States

Re: Spaces folder names in FOR loop

#3 Post by ShadowThief » 12 Aug 2021 09:38

The one place you needed quotes was around %remove%. However, because this is a file, you need to tell for /f that the thing in quotes is a file and not a string, so you also need to add the usebackq option.

Code: Select all

for /f "usebackq delims=" %%f in ("%remove%") do del /Q "%%f" 2>NUL

rscanny
Posts: 2
Joined: 12 Aug 2021 03:40

Re: Spaces folder names in FOR loop

#4 Post by rscanny » 13 Aug 2021 01:41

ShadowThief wrote:
12 Aug 2021 09:38
The one place you needed quotes was around %remove%. However, because this is a file, you need to tell for /f that the thing in quotes is a file and not a string, so you also need to add the usebackq option.

Code: Select all

for /f "usebackq delims=" %%f in ("%remove%") do del /Q "%%f" 2>NUL
This worked perfectly, thanks for your help!

Post Reply