Dima
Dima

Reputation: 25

Remove empty directories and directories which contain only specific file (batch file)

I need a batch file which remove all empty directories and directories which contain only specific file (.svn).Thank you very much for any help.

Example :

Folder1                       -- folder conatins subfolders with some files, not remove
     Folder2                  -- empty folder, folder should be deleted
     Folder3                  -- folder contains only .svn, folder should be deleted
           .svn
     Folder4                  -- folder contains subfolder with file, not remove
           Folder41           -- folder contains some file, not remove
                somefile.dat
     Folder5                  -- folder contains some file, not remove 
           .svn
           somefile.dat
     Folder6                  -- folder contains empty subfolders, folder should be deleted
           Folder61           -- folder contains only specific file, folder should be deleted
                .svn

Result:

Folder1
     Folder4    
           Folder41
                somefile.dat
     Folder5
           .svn
           somefile.dat

Upvotes: 0

Views: 597

Answers (1)

dbenham
dbenham

Reputation: 130919

I was surprised at how little code this takes. The biggest trick is to use SORT /R on the output of DIR /B /S /AD so that you can process the child nodes prior to processing the parent nodes of the folder hierarchy.

I've quickly tested the code, but please test yourself in a safe manner.

This 1st version assumes ".SVN" is the full file name.

@echo off
setlocal disableDelayedExpansion
for /f "eol=: delims=" %%A in ('dir /b /s /ad ^| sort /r') do (
  dir /b "%%A" | findstr /livx ".svn" >nul || rd /s /q "%%A"
)

The 2nd version is only slightly modified in case you meant "*.SVN". Only one FINDSTR option is changed.

@echo off
setlocal disableDelayedExpansion
for /f "eol=: delims=" %%A in ('dir /b /s /ad ^| sort /r') do (
  dir /b "%%A" | findstr /live ".svn" >nul || rd /s /q "%%A"
)

Update: 2012-11-06

I just realized that the above solution(s) can be defeated if a non-empty folder is named .SVN. The code should remove folders that are either empty or only contain a file named .SVN. It should not remove a folder if it contains a non-empty folder named .SVN.

Below is a fix for the first solution:

@echo off
setlocal disableDelayedExpansion
for /f "eol=: delims=" %%A in ('dir /b /s /ad ^| sort /r') do (
  dir /b "%%A"|findstr /livx ".svn" >nul||>nul 2>&1 dir /b /ad .svn||rd /s /q "%%A"
)

And here is a fix for the second solution

@echo off
setlocal disableDelayedExpansion
for /f "eol=: delims=" %%A in ('dir /b /s /ad ^| sort /r') do (
  dir /b "%%A"|findstr /live ".svn" >nul||>nul 2>&1 dir /b /ad *.svn||rd /s /q "%%A"
)

Upvotes: 1

Related Questions