views:

784

answers:

3

I need to write a command in a .bat file that recursively deletes all the folders starting with a certain string. How may I achieve this ?

+4  A: 

Unfinished, I think. If you meant "Recursively go down a directory hierarchy to delete all folders starting with a certain string", then the following might suffice:

for /f "delims=" %%x in ('dir /b /ad abc*') do rd /s /q "%%x"

This will recurse into the directory tree, finding all folders starting with "abc", iterate over that list and removing each folder.

Maybe you need to wrap an if exist around the rd depending on the order in which directories are found and returned. In general, iterating over something and changing it at the same time is rarely a good idea but sometimes it works :-)

Joey
@Johannes Rössel: did this work? It doesn't work when trying to delete directories ending with ".delme", I tried your suggestion like this: for /f "delims=" %%x in ('dir /b /ad *.delme') do rd /s /q "%%x" BUT IT DOES NOT SEEM TO WORK.
Marco Demajo
@Marco: No need to shout. If in doubt, ask a new question and tell your problems clearly and in detail. Something like »Doesn't work« is usually a bad issue report.
Joey
@Johannes Rossel: wasn't shouting, I just wrote upper case. I'll ask new question then.
Marco Demajo
+2  A: 

How about:

for /d %a in (certain_string*) do rd /s %a

This will work from the command prompt. Inside a batch file, you would have to double the %s, as usual:

@echo off
for /d %%a in (certain_string*) do rd /s %%a
Greg Hewgill
Ouch. I need more sleep ... or tea ... *(hits head on the table)*
Joey
Hmm, although that probably won't recurse into the dir tree and find deeper folders matching the criteria, right? (My solutions don't do that as well, but I just realized that's what the OP meant).
Joey
I had to expand this a bit from my original simple attempt, because `rd` doesn't appear to expand wildcards by itself.
Greg Hewgill
To recursively look for directories starting with a prefix, you may be able to use `for /r` or some combination thereof.
Greg Hewgill
Oh, not nice. I didn't try it either since I currently have no directories lying around to wreck :-)
Joey
@Greg Hewgill: did this work? It doesn't work when trying to delete directories ending with ".delme", I tried your suggestion like this: for /d %%x in (*.delme) do rd /s /q "%%x" BUT IT DOES NOT SEEM TO WORK.
Marco Demajo
+1  A: 

This is the complete answer you are looking for:

FOR /D /R %%X IN (certain_string*) DO RD /S /Q "%%X"

where obviously you need to replace 'certain_string' with the string your folders start with.

This deletes RECURSIVELY as you asked (I mean it goes throught all folders and subfolders).

Marco Demajo
Nothing other than @Maorco's answer worked for me. Sadly he has not got any votes other than mine. :(
Ismail