Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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!

share|improve this question
up vote 4 down vote accepted

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.

share|improve this answer
    
@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

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

del /f /s /q c:\windows\lock
share|improve this answer

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
share|improve this answer

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.

share|improve this answer
    
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 at 10:55

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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