Search code examples
batch-filecmd

Delete all files of specific type (extension) recursively down a directory using a batch file


I need to delete all .jpg and .txt files (for example) in dir1 and dir2.

What I tried was:

@echo off
FOR %%p IN (C:\testFolder D:\testFolder) DO FOR %%t IN (*.jpg *.txt) DO del /s %%p\%%t

In some directories it worked; in others it didn't.

For example, this didn't do anything:

@echo off
FOR %%p IN (C:\Users\vexe\Pictures\sample) DO FOR %%t IN (*.jpg) DO del /s %%p\%%t

What I'm I missing in the second snippet? Why didn't it work?


Solution

  • You can use wildcards with the del command, and /S to do it recursively.

    del /S *.jpg

    Addendum

    @BmyGuest asked why a downvoted answer (del /s c:\*.blaawbg) was any different than my answer.

    There's a huge difference between running del /S *.jpg and del /S C:\*.jpg. The first command is executed from the current location, whereas the second is executed on the whole drive.

    In the scenario where you delete jpg files using the second command, some applications might stop working, and you'll end up losing all your family pictures. This is utterly annoying, but your computer will still be able to run.

    However, if you are working on some project, and want to delete all your dll files in myProject\dll, and run the following batch file:

    @echo off
    
    REM This short script will only remove dlls from my project... or will it?
    
    cd \myProject\dll
    del /S /Q C:\*.dll
    

    Then you end up removing all dll files form your C:\ drive. All of your applications stop working, your computer becomes useless, and at the next reboot you are teleported in the fourth dimension where you will be stuck for eternity.

    The lesson here is not to run such command directly at the root of a drive (or in any other location that might be dangerous, such as %windir%) if you can avoid it. Always run them as locally as possible.

    Addendum 2

    The wildcard method will try to match all file names, in their 8.3 format, and their "long name" format. For example, *.dll will match project.dll and project.dllold, which can be surprising. See this answer on SU for more detailed information.