How to delete all files that don't have a certain string in their name
Solution 1:
How can I delete zip files in a folder/subfolders that don't have "MS" in their name?
Use the following batch file:
@echo off
setlocal disableDelayedExpansion
for /f "usebackq tokens=*" %%i in (`dir /a:-d /b /s *.zip ^| findstr /v "[\\][^\\]*MS[^\\]*$"` ) do (
echo del /s /q %%i
)
endlocal
Notes:
- Remove the
echo
when you are happy with what the batch file will do. - Answer updated as per comment by dbenham to allow for directories containing the string "MS"
- Answer updated to handle filenames containing spaces.
Further Reading
- An A-Z Index of the Windows CMD command line - An excellent reference for all things Windows cmd line related.
- del - Delete one or more files.
- dir - Display a list of files and subfolders.
- findstr - Search for strings in files.
- for /f - Loop command against the results of another command.