Windows – Delete set of files using find command

batchcommand linewindows

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!

Best Answer

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.

Related Question