Closed 9 years ago.
- This question does not appear to be about a specific programming problem, a software algorithm开发者_JAVA技巧, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
- Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Is there a way to delete all empty sub-directories below a given directory from a batch file?
Or is it possible to recursively copy a directory, but excluding any empty directories?
You really have two questions:
1. Is there a way to delete all empty sub-directories below a given directory from a batch file?
Yes. This one-line DOS batch file works for me. You can pass in an argument for a pattern / root or it will use the current directory.
for /f "delims=" %%d in ('dir /s /b /ad %1 ^| sort /r') do rd "%%d" 2>nul
The reason I use 'dir|sort' is for performance (both 'dir' and 'sort' are fairly fast). It avoids the recursive batch function solution used in one of the other answers which is perfectly valid but can be infuriatingly slow :-(
2. Or is it possible to recursively copy a directory, but excluding any empty directories?
There are a number of ways to do this listed in other answers.
To copy ignoring empty dirs you can use one of:
robocopy c:\source\ c:\dest\ * /s
xcopy c:\source c:\dest\*.* /s
@echo off
setlocal ENABLEEXTENSIONS
call :rmemptydirs "%~1"
goto:EOF
:rmemptydirs
FOR /D %%A IN ("%~1\*") DO (
REM recurse into subfolders first...
call :rmemptydirs "%%~fA"
)
RD "%~f1" >nul 2>&1
goto:EOF
Call with: rmemptydirs.cmd "c:\root dir to delete empty folders in"
xcopy's /s will ignore blank folder when copying
xcopy * path\to\newfolder /s /q
This batch file does the trick just fine from any path, in my case I use Windows Environment variable IWAY61 :
@echo off
cd %IWAY61%
for /f "usebackq delims=" %%d in (`"dir /ad/b/s | sort /R"`) do rd "%%d"
精彩评论