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!

0

4 Answers 4

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.

2
  • @DaveJarvis Your welcome. Dec 17, 2012 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. Dec 17, 2012 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.

1
  • 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, 2016 at 10:55

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .