Monday, October 12, 2009

find -exec equivalent for Windows cmd

I was looking for replacement of the shell (bash) command:
find -name '.svn' -exec rm -rf {} \;

for Windows cmd.exe.

The purpose is to remove all .svn directories from a directory recursively.

In cmd you can do dir /b /s to list directories in plain format including its subdirectories. For example:

C:\WINDOWS\system32\config>dir /s /b
C:\WINDOWS\system32\config\AppEvent.Evt
C:\WINDOWS\system32\config\system.sav
C:\WINDOWS\system32\config\systemprofile
C:\WINDOWS\system32\config\userdiff
C:\WINDOWS\system32\config\systemprofile\Desktop
C:\WINDOWS\system32\config\systemprofile\Favorites
C:\WINDOWS\system32\config\systemprofile\My Documents
C:\WINDOWS\system32\config\systemprofile\Start Menu

...

That format is already similar to what find command does. So how to execute a program with arguments taken from this list?

The answer is, use the FOR command with /F "usebackq" switch.

So, we put the command in backquotes, like this:

for /F "usebackq" %i in (`dir /s /b *.svn`) do rmdir /s /q %i

Problem solved. Remember to double the percent sign if you do this in a batch file.