Using wildcards with the rmdir or rd command

Let's say there are some folder in the D: drive:

D:\Air
D:\Abonden
D:\All
D:\Whatever

I want to delete all folders starting with "A" (including all subfolders and files). I tried this command:

rmdir D:\A* /s /q

I get an error, though :(

The filename, directory name, or volume label syntax is incorrect.

The del command works with *, but I need to delete folders as well.
Is there a way to achieve that via the rmdir command?


Solution 1:

cd c:\temp
for /f %i in ('dir /a:d /s /b A*') do rd /s /q %i

Use this to test though:

for /f %i in ('dir /a:d /s /b A*') do echo rd /s /q %i

This will pipe out the commands to be run into the command prompt and allows you to see what's going on.

Bear in mind that this will also search subfolders such as "C:\temp\jjj\aaa" and would delete the aaa folder. If you want it to just look at top level folders "C:\temp\aaa", then remove the "/s" from the command.

The key to this is the A*, where you would put in your search string. This will accept wildcards such as aaa*, aaa* and *aaa* if you want it to.

Solution 2:

Deleting folders using wildcards

The rmdir / rd command alone doesn't support wildcard characters (that is, * and ?). You can workaround this limitation by wrapping it in a for loop.

Example usage

for /d %G in ("X:\A*") do rd /s /q "%~G"

Note As you're deleting files and folders, you might want to replace the rd command with echo first. This way you can ensure anything that shouldn't be deleted actually would.

Multiple patterns

In order to delete multiple folders matching different patterns the syntax is not too different. As @dbenham correctly pointed out, a one-line command is enough. You can also specify different paths:

for /d %G in ("X:\A*","Y:\Whatever\B*","Z:\C?D") do rd /s /q "%~G"

Bonus - Checking folder existence

In case you want to check whether specific folders exist, you can use the following command:

dir /b /a:d "X:\A*" >nul 2>&1 && echo Folders exist. || echo No folders found.

Further reading

  • for /d - Loop through directory
  • Conditional execution
  • Command-Line Reference