Page 1 of 1
Spaces folder names in FOR loop
Posted: 12 Aug 2021 03:50
by rscanny
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
Re: Spaces folder names in FOR loop
Posted: 12 Aug 2021 09:04
by kwsiebert
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.
Re: Spaces folder names in FOR loop
Posted: 12 Aug 2021 09:38
by ShadowThief
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
Re: Spaces folder names in FOR loop
Posted: 13 Aug 2021 01:41
by rscanny
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!