0

I am trying to write a Windows batch script that should delete any file but .zip in a folder, however the command that I use does not work for files that have white spaces in their filename and I cannot find how to fix it:

for /f %%F in ('dir /b /a-d ^| findstr /vile ".zip"') do del "%%F"

I have tried with various options of the command but did not work

Compo
  • 36,585
  • 5
  • 27
  • 39
Eg It
  • 5
  • 2
  • The command line to use is: `for /F "eol=| delims=" %%G in ('dir /A-D /B 2^>nul ^| %SystemRoot%\System32\findstr.exe /E /I /L /V ".zip"') do del /A /F "%%G"` to delete all files __except__ `.zip` files, even those containing a space in file name or having a file name beginning with a semicolon or having the hidden or the read-only attribute set. – Mofi Jan 09 '23 at 16:07
  • Does this answer your question? [Batch delete all files and directories except specified file and directory](https://stackoverflow.com/questions/57108602/batch-delete-all-files-and-directories-except-specified-file-and-directory) – Zephyr Jan 09 '23 at 19:48

1 Answers1

0

Your problem is explained well here: https://ss64.com/nt/for_f.html

The relevant part says:

By default, /F breaks up each line within the file at each blank space " ", and any blank lines are skipped, this default parsing behavior can be changed by applying one or more of the "options" parameters. The option(s) must be contained "within quotes"

The way to do that in your case is to tell for that it should not consider spaces as delimiters, in fact you don't want any delimiters:

for /f "delims=" %%F in ('dir /b /a-d ^| findstr /vile ".zip"') do echo "%%F"

(I changed the command to echo, since I don't want careless people accidentally deleting files because you or I made a mistake :) - once you convinced yourself it's good, change it back to del)

Edit: updated to include quotes in command, as indicated in comments.

Grismar
  • 27,561
  • 4
  • 31
  • 54
  • 1
    Thank you it works! Just one note, when using the DEL %%F the argument should be placed within double quotes otherwise files with spaces in their filename won't be deleted: for /f "delims=" %%F in ('dir /b /a-d ^| findstr /vile ".zip"') do DEL "%%F" – Eg It Jan 10 '23 at 00:19