3

Background

Delete a set of files, scattered across different directories.

Problem

The following code does not work (the unescaped | causes issues);

for %i in (dir /s/b | find "lock") do echo del %i

Question

Without writing a batch file, how would you delete all files named "lock" (i.e., found using the find command) within the current directory and all subdirectories (including hidden directories)?

Thank you!

4

Your code needs a few touchups. The pipe operator needs to be escaped by the batch escape character ^ and when using quotations within the parentheses for a command, the usebackq option must be specified.

for /?

Batch Format:

for /f "usebackq" %%i in (`dir /s /b ^| find "lock"`) do echo %%i

Command Line Format:

for /f "usebackq" %i in (`dir /s /b ^| find "lock"`) do echo %i

Replace echo with del and any of its options when you want it to actually delete the files. Note the double percent signs are needed when used within a bat file, single when used directly on the command line.

Another method is to use the forfiles command. forfiles /?

forfiles /m *lock* /s /c "cmd /c echo @file"

Note, both of these methods will also delete any folders that contain the search term lock. Additional steps would be needed to be taken to prevent this.

  • @DaveJarvis Your welcome. – David Ruhmann Dec 17 '12 at 22:18
  • @DaveJarvis You may also want to add the /l option to the dir command to cause a pure lowercase comparison, or add the /i option to the find command to cause a case-insensitive comparison. – David Ruhmann Dec 17 '12 at 22:24
2

For a given drive and/or path (looks in subfolders also):

del /f /s /q c:\windows\lock
1

david-ruhmann answer doesn't work with path containing spaces! You can use:

for /f "usebackq delims=" %i in (`dir /s /b ^| find "lock"`) do del "%i" 

If you have hinned files you can use:

for /f "usebackq delims=" %i in (`dir /s /b /a ^| find "lock"`) do del "%i" /A:H
1

Another option would be to directly use the del command as follows:

del /s c:\directory\*_gdiplus*.*

where "_gdiplus", e.g., is the filename that contains the string you want to be deleted.

  • If you don't format your code properly it won't display all the characters. See Markdown help. I've fixed it for you this time, but please pay attention to this in future. – DavidPostill Jun 14 '16 at 10:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.