windows 如何从批处理文件中仅删除空目录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2697885/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to delete only empty directories from a batch file
提问by M4N
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?
或者是否可以递归复制目录,但不包括任何空目录?
回答by Adisak
You really have two questions:
你真的有两个问题:
1. Is there a way to delete all empty sub-directories below a given directory from a batch file?
1. 有没有办法从批处理文件中删除给定目录下的所有空子目录?
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.
是的。这个单行 DOS 批处理文件对我有用。您可以为模式/根传递参数,否则它将使用当前目录。
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 :-(
我使用 'dir|sort' 的原因是为了性能('dir' 和 'sort' 都相当快)。它避免了在其他答案之一中使用的递归批处理函数解决方案,这是完全有效的,但可能会非常慢:-(
2. Or is it possible to recursively copy a directory, but excluding any empty directories?
2. 或者是否可以递归复制目录,但不包括任何空目录?
There are a number of ways to do this listed in other answers.
其他答案中列出了多种方法来执行此操作。
回答by Alex K.
To copy ignoring empty dirs you can use one of:
要复制忽略空目录,您可以使用以下之一:
robocopy c:\source\ c:\dest\ * /s
xcopy c:\source c:\dest\*.* /s
回答by YOU
xcopy's /s will ignore blank folder when copying
xcopy 的 /s 将在复制时忽略空白文件夹
xcopy * path\to\newfolder /s /q
回答by Anders
@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"
致电: rmemptydirs.cmd "c:\root dir to delete empty folders in"
回答by user2451910
This batch file does the trick just fine from any path, in my case I use Windows Environment variable IWAY61:
这个批处理文件从任何路径都可以很好地完成这个技巧,在我的情况下,我使用 Windows 环境变量IWAY61:
@echo off
cd %IWAY61%
for /f "usebackq delims=" %%d in (`"dir /ad/b/s | sort /R"`) do rd "%%d"