131

I have a directory on my Windows 7 machine that has hundreds if not thousands of sub-directories. Some of them have files, some do not. I want to delete all the empty directories.

Looking at the del and rmdir DOS command, it does not look like you can recursively do this without deleting all the files. Is there a way to do this from the command line?

Hennes
  • 65,142
mohlsen
  • 1,482

13 Answers13

152

You can use Remove Empty Directories utility.

Alternatively you can use this one-liner batch file (from DownloadSquad):

for /f "delims=" %d in ('dir /s /b /ad ^| sort /r') do rd "%d"

(if used inside a batch file, replace %d with %%d)

This works because rd will not remove a directory that contains files.

user198350
  • 4,019
caliban
  • 20,153
  • 9
    P.S I suggest you try the GUI-based tool first, before trying any command-line commands that can potentially delete all files. – caliban Sep 11 '09 at 13:50
  • that tool looks good. I will check it out and report back – mohlsen Sep 11 '09 at 14:31
  • Using the batch version gives me an error: The system cannot find the file dir /ad/b/s | sort /R. – EBGreen Sep 11 '09 at 15:58
  • Hang on, testing command in my Windows VM. – caliban Sep 11 '09 at 16:02
  • Also the batch version would not handle spaces in the directory names. I'm pretty sure that it would not remove a directory that contained only empty sub directories either. – EBGreen Sep 11 '09 at 16:06
  • Got it, couple of errors with the DownloadSquad's command (!!). I've amended in my answer. :) – caliban Sep 11 '09 at 16:13
  • Still won't delete a directory that contains an empty directory. – EBGreen Sep 11 '09 at 17:59
  • 1
    Make sure it is truly empty. A hidden desktop.ini is still considered a file. same as a thumbs.db. If you want to verify whether this works, create a test directory with directories inside that are empty and populated. It works, I've verified. – caliban Sep 11 '09 at 18:19
  • 1
    Yep. It works. My mistake. – EBGreen Sep 11 '09 at 18:27
  • 10
    for /f %d in ('dir /s/b') do rmdir "%d" should work as rmdir cannot remove a non-empty folder – seanyboy Sep 16 '09 at 13:14
  • RED is the best tool for this, since it handles directories with nothing but junk in them (Thumbs.db, .DS_Store), lets you permanently protect directories from deletion, shows a nice tree view, etc. I got it working in Windows 7 using the compatibility troubleshooter thing. There's also a list of alternative tools at the bottom of the RED web site. – endolith Jan 19 '10 at 20:59
  • This doesn't work if the folder is set to read only. – shinzou Jul 19 '15 at 22:14
  • 1
    Look at http://stackoverflow.com/a/34025977/694360 to find out how to add this functionality to context menu. – mmj Dec 01 '15 at 17:36
  • The for loop command worked perfectly. – Aaron Reed Mar 01 '16 at 02:22
  • 5
    Just a warning, this script destroys directory junctions too. I learned this the hard way. – Pyroglyph May 22 '16 at 15:56
  • @Pyroglyph: Can you edit the answer (I don't fully understand what this means)? – user198350 Oct 13 '17 at 16:25
  • I get this error: "sort: cannot read: /r: No such file or directory" UPDATE: Ah, my cmd is using Git-for-Windows' git\usr\bin\sort.exe instead of `system32\sort.exe). – Dai Feb 19 '20 at 05:29
100

You can also use ROBOCOPY. It is very simple and can also be used to delete empty folders inside large hierarchy.

ROBOCOPY folder1 folder1 /S /MOVE

Here both source and destination are folder1, as you only need to delete empty folders, instead of moving other files to different folder. /S option is to skip copying(moving, in the above case) empty folders. It is also faster as the files are moved inside the same drive.

Varun Sharma
  • 1,126
  • 4
    Magic. So this moves all non-empty folders to the very same location they were already in (so does nothing?), and skips empty folders? But then: why would skipping them result in deletion? And wouldn't this move nested folders into folder1? Scary, unless tested well. – Arjan Sep 13 '15 at 11:15
  • 4
    @Arjan I have tested it, and it works perfectly!. To understand its working, its like moving all files to different location, except empty folders, and then deleting the left-behind empty-folders. /MOVE copies the files first, and then deletes the source file after copying. So, as /S is used, it copies the non-empty folders to destination(same folder in the above case). Then, it deletes the empty folders(like, its thinking that empty-folders has already been copied). No, it does not move nested folders into folder1, as ROBOCOPY moves folders recursively. – Varun Sharma Sep 13 '15 at 19:56
  • 4
    it even works with UNC paths (at least on win7) ! Brilliant ! – Arioch 'The Oct 15 '15 at 14:11
  • Can Robocopy move files to the recycle bin? – user198350 Oct 13 '17 at 16:37
  • 3
    This is a very elegant solution without any third-party software needed. Thank you! – Marcus Mangelsdorf Dec 28 '17 at 20:20
  • 2
    This just did its magic and worked perfectly. Thanks! – CharleyDC5 Apr 23 '19 at 14:36
  • 1
    Varun thanks. This is an awesome solution. Went through 3.8TB of files across 60,000 folders in about 10 minutes. Not a single file lost, but no more empty directories. Beautiful. – SimonGoldstone Aug 15 '19 at 10:34
  • LOVE IT robocopy.exe are in win8 or win10 : ROBOCOPY %temp% %temp% /S /MOVE and its clean my temp from e,pty folders who – user956584 Aug 07 '20 at 17:23
  • 2
    This is fantastic. A couple notes; first this correctly solves a reported problem with the accepted answer where directories containing only empty directories would not be removed. It's not trivial to fix in that approach because it requires removal in depth-first order. This robocopy technique fully removes empty structures to any level of depth. Second, it's worth mentioning that no files are actually moved by robocopy here. This is important for performance of course, but it also means that no NTFS file identifier (FRN) numbers or USN journals are unnecessarily changed or recorded. – Glenn Slayden Sep 08 '20 at 23:55
  • I think Robocopy requires folder names with spaces to be enclosed in double quotes, and backslashes in path names to be replaced with double backslashes. – Ray Woodcock Dec 26 '20 at 16:51
  • Be careful of junctions, directory links, file links, etc... they will be followed and can cause some unexpected results. When running it on a Windows Users folder from another drive, be ware of the Music, Documents, Videos links etc. – David d C e Freitas Feb 23 '22 at 14:11
  • This is is one of my all-time most revisited stackexchange answers thank you!! – Mr. T Mar 15 '22 at 19:30
  • 1
    This saved me so much time when trying to clear an important folder containing hundreds of thousands of empty folders plus a handful of important, non-empty folders in between. For performance reasons I added the switches to not output to the console, and robocopy blazed like a flaming torch through the job: /NFL /NDL /NJH /NJS – GrahamMc Apr 12 '23 at 11:36
18

Since Cygwin comes with GNU find, you can do this:

find . -type d -empty -delete

Or to avoid the noise when a folder no longer exists:

find . -type d -empty -execdir rmdir {} +
Gareth
  • 18,809
7

Hmmm... maybe even simpler solution:

for /d /r %d in (*.*) do rd "%d"

Start this from the folder you want empty folders to be deleted.

/d - will work on folders, not files /r - will recurse subdirs

  • Thanks. Found that this only applies to commandline not batchfiles. According to https://superuser.com/questions/444474/how-to-delete-empty-folders-from-a-given-directory-in-windows-with-a-script by Dennis, if we want to use this in a batchfile it should be for /f "delims=" %%i in ('dir /s /b /ad ^| sort /r') do rd "%%i". The for behaviour is slightly different between commandline and batchfiles. – Brian Mar 10 '21 at 22:21
  • This does not work for me when I have nested empty folders. I think it starts at the top of the hierarchy, so the folders aren't empty. You could just run it repeatedly until it gets them all, though. – ChaosFreak Aug 07 '22 at 01:22
7

The free utility EmptyFolderNuker does this fine, from a base folder of your choice. It also removes those directories only containing empty sub-directories.

Rob Kam
  • 1,866
  • 1
    The one-liner batch file didn't work for me (I get the error "%%d was unexpected at this time."), and the Remove Empty Directories program will not install (it says on the linked page that it is not compatible with Windows 7 anyway).

    This program worked like a charm.

    – Phoenix Mar 07 '10 at 11:52
  • 1
    As user36580 wrote below, "it is likely you are running directly from the command line. In that case, change the double %% to a single %" – Lachlan McDonald Jul 15 '12 at 03:27
  • 1
    I like this over the pure command-line version as it allows you to preview the things that get deleted. You can always call it from the command-line using "%~dp0\EmptyFolderNuker.exe" %cd%. – Jeroen Wiert Pluimers Dec 27 '14 at 14:30
  • 1
    @rob-kam The URL for "EmptyFolderNuker" isn't available anymore. – PeterCo Aug 09 '19 at 08:13
  • @PeterCo Thanks, fixed now. – Rob Kam Aug 12 '19 at 19:49
0

Combining Gareth's and G-Man's posts:

find . -depth -type d -empty -execdir rmdir {} +

Edit: But that gave a security error because of 'C' in my PATH var...so instead:

$find . -depth -type d -empty | while read dir; do (rmdir -v $dir); done

I don't use xargs because it appears to have an input line limit (of about 1024 lines, I think?), whereas

 while read x; do (command $x); done

just keeps on going for as long as it has input. Leave out the '-v' verbose flag if you don't want to see the results and/or want it to run faster.

0

None of the previous answers worked for me, so I made the following file:

EmptyDirectoriesRemove.cmd

Contents:

@setlocal enableextensions enabledelayedexpansion

:walk_tree
for /D %%d in (*) do (
cd %%d
@CALL :walk_tree %%d
cd ..
rd %%d
)

endlocal

Usage: Cd to the top level directory you want to clean up. From the command line prompt, run:

EmptyDirectoriesRemove.cmd

Warnings will show up for non-empty directories.

Usual disclaimers: Use at your risk. Backup before testing. etc.

0

The 4NT shell (nowadays Take Command) has a /sx option to "DEL". /S is recursive, the appended X is remove empty dirs.

0

You can use Powershell:

Get-ChildItem "Path" -recurse | 
  Where-Object {($_.PSIsContainer -eq $true) -and ((gci $_.fullName).count -eq 0)} | 
    Remove-Item -Force
Wasif
  • 8,474
0

You can use vbscript to do this:

' Save in deleteEmptyFolders.vbs
' call with:
' cscript deleteEmptyFolders.vbs C:\RootFolder
If WScript.Arguments.Count > 0 Then
  directory = WScript.Arguments.Item(0)
  WSH.Echo("Deleting empty folders starting from " & directory)
Else
  WSH.Echo "Please supply a directory as an argument"
  WSH.Quit
End If

Set ofso = CreateObject("Scripting.FileSystemObject") Set rootFolder = ofso.GetFolder(directory)

Sub DeleteEmptySubfoldersIn(folder) For Each subfolder in folder.SubFolders On Error Resume Next '' VBScript TRY ' The script can error out if you don't have permissions to delete ' the subfolder DeleteEmptySubfoldersIn subfolder Next

''WScript.Echo folder.Path If folder.Files.Count = 0 And folder.SubFolders.Count = 0 Then 'TEST: print what you'll delete WScript.Echo "Was going to delete " & folder.Path & " b/c it's EMPTY"

'DISARMED uncomment line below to make it work
'''''ofso.DeleteFolder folder

End If End Sub

DeleteEmptySubfoldersIn rootFolder

bobobobo
  • 5,360
0

To delete empty folders while excluding hidden files

To delete empty folders while excluding hidden files using the command prompt (cmd), you can use a combination of the dir, for, and rd commands in Windows. Here's a step-by-step guide:

  1. Open Command Prompt: Press Win + R, type cmd, and hit Enter.

  2. Navigate to the directory where you want to start the deletion process. You can use the cd command to change directories. For example:

    cd "C:\Your\Directory\Path"
    
  3. Run the following command to delete empty directories while excluding hidden files:

    for /f "delims=" %d in ('dir /ad /b /s ^| sort /r') do @(dir /a-d /b "%d" | findstr "." >nul || rd /s /q "%d")
    

This command will recursively search for all directories (/ad), list them (/b for bare format), and sort them in reverse order (/s for recursive, sort /r to reverse). Then, for each directory found, it checks if it contains any files (excluding hidden files) using dir /a-d and findstr ".". If no non-hidden files are found, it deletes the directory using rd /s /q.

Remember to replace C:\Your\Directory\Path with the actual path of the directory you want to clean up. And as always, be cautious when deleting files and folders, as this operation is irreversible. Make sure you have a backup of important data before proceeding.


To delete empty folders while including hidden files

To delete empty folders while including hidden files, you can use a similar approach but modify the command to include hidden files as well. Here's how you can do it:

for /f "delims=" %d in ('dir /ad /b /s ^| sort /r') do @(dir /a /b "%d" | findstr "^" >nul || rd /s /q "%d")

This command will delete empty directories while including hidden files in the check for emptiness. Here's what each part of the command does:

  • for /f "delims=" %d in ('dir /ad /b /s ^| sort /r') do: This loop iterates over all directories (/ad) recursively (/s) in bare format (/b) sorted in reverse order (sort /r).

  • dir /a /b "%d": Lists all files and directories, including hidden ones (/a), in the specified directory ("%d") in bare format (/b).

  • findstr "^" >nul: This command checks if any files or directories are found in the specified directory. If nothing is found, it outputs nothing (redirected to nul), indicating that the directory is empty.

  • rd /s /q "%d": Deletes the specified directory ("%d") recursively (/s) without prompting (/q) if it's empty.

Make sure to replace C:\Your\Directory\Path with the actual path of the directory you want to clean up. As always, exercise caution when deleting files and folders, especially with recursive commands, and ensure you have a backup of important data.

Ste
  • 1,226
0

If you have Cygwin installed, you could do this:

find -type d -exec rmdir {} \;
0

If you're working in emacs (making this platform-agnostic), the following works:

(defun *-delete-empty-directories (root-directory)
  "Recursively delete empty directories in ROOT-DIRECTORY.

When called from dired, `dired-current-directory' is used for
ROOT-DIRECTORY."

  ;; Interface
  (interactive (list (if (eq major-mode 'dired-mode)
                         (expand-file-name (dired-current-directory))
                       (read-from-minibuffer "Root directory: "))))
  (when (or (null root-directory) (string= "" root-directory))
    (user-error "No root directory provided"))
  (when (called-interactively-p 'interactive)
    (unless (yes-or-no-p (format "Delete all non-empty directories in `%s'? "
                                 root-directory))
      (user-error "Directory `%s' has been left untouched" root-directory)))

  ;; Implementation
  (require 'f)
  (let ((entries (f-directories root-directory)))
    (while entries
      (let ((curdir (car entries)))
        (when (f-directories curdir)
          (*-delete-empty-directories curdir))
        (unless (f-entries curdir)
          (delete-directory curdir)
          (message "Directory deleted: `%s'" curdir))
        (setq entries (cdr entries)))))
Sean Allred
  • 1,252
  • ...Please tell me you wouldn't have to type all of this in order to accomplish this in emacs. – Hashim Aziz Dec 31 '16 at 00:56
  • 1
    @Hashim The idea is that you have it defined in your init and then bound to a key. Technically I could have it bound to D if I wanted to, but since I don't have a common need for this, all I have to type is M-x *ded RET and bam–done. (If I did indeed have to type this every time, you're absolutely right that it'd be absurd – luckily that's not the case.) – Sean Allred Jan 01 '17 at 07:33
  • Fair enough, that sounds more plausible. – Hashim Aziz Jan 01 '17 at 22:30
  • Does M-x *ded RET have any significance or is it random? If the latter, how do you keep track of all the shortcuts you've assigned in emacs? Does memorisation suffice or do you find yourself having to look them up? – Hashim Aziz Jan 01 '17 at 22:32
  • 1
    @Hashim *ded is an abbreviation for the full function name *-delete-empty-directories. Many completion engines (such as ivy, the one I use) understand this kind of fuzzy matching. As for keeping them memorized… I simply don't have to. The functions I've defined all start with * so I can easily find them if they're not bound to a key. Otherwise, emacs itself will tell me if there was a faster way of calling the function. If all else fails, there's always apropos. – Sean Allred Jan 02 '17 at 02:10
  • Can the downvoter please describe what should be improved upon in this answer? It's a valid approach. – Sean Allred Feb 07 '19 at 00:00