How to delete all files that don't have a certain string in their name

4

I have seen Deleting all files that do not match a certain pattern - Windows command line

However, I have not seen anything regarding how to delete everything that does not contain a certain string within its file name.

How can I delete all zip (other files should not be effected) files in a folder and its subfolders that don't have "MS" (case sensitive) in their file name.

These letters may be next to other letters (eg. a file names "ABCMSABC" should be kept because it has "MS" in it, but all other files should be deleted). Multiple files will have "MS" in them.

User093203920

Posted 2016-03-16T00:30:30.813

Reputation: 213

To at least point you in the right direction using the command line: You will probably need to use some combination of the "for" command (to loop through folders recursively), "dir", the "findstr" command with regular expressions (to weed out the files that don't contain "MS"), and then delete that result. – BrianC – 2016-03-16T02:44:44.097

@BrianC Regexp is not needed in the findstr – DavidPostill – 2016-03-16T09:46:03.767

@DavidPostill true. I forgot about the /v option. – BrianC – 2016-03-16T13:18:34.050

@BrianC Never mind. You were correct. Regexp is required for a robust solution. – DavidPostill – 2016-03-16T19:14:36.917

Answers

5

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

DavidPostill

Posted 2016-03-16T00:30:30.813

Reputation: 118 938

1That is a good start, but you need a more sophisticated regex search for FINDSTR. Your current code can fail to delete a zip file without MS if the folder path to the file contains MS. I would use "[\\][^\\]*MS[^\\]*$" – dbenham – 2016-03-16T13:45:01.233

1@dbenham Good point. Thanks. Testing your regexp I also realised that my answer didn't handle filenames with spaces ;) Updated. – DavidPostill – 2016-03-16T13:46:26.613