bat批处理复制指定目录及子目录文件夹树结构
仅仅复制目录结构,不复制任何文件。保存以下内容到cef.bat文件
@echo off
:mkdir
setlocal enabledelayedexpansion
if [%2]==[] (echo [%time%] The destination folder is null. & goto :eof)
for /d %%a in (%1*) do (
set p=%%a\
set p=!p:.\"=..\"!
echo exec md "%2\!p!"
md "%2\!p!"
call :mkdir "!p!" %2
)
endlocal
执行方式,如:cef "" c:\tmp
优化1
根据上面的代码,再次优化,可以指定复制层数
@echo off
cls
echo [%time%] copy empty folder
rem pLevel可设置复制几层文件夹
set pLevel=2
:mkdir
setlocal enabledelayedexpansion
if [%2]==[] (echo [%time%] The destination folder is null. & goto :eof)
set fp=%1
set fp=%fp: =%
set fp=%fp:"=%
set fp=%fp:\= %
set pCount=0
for %%i in (%fp%) do set /a pCount+=1
if %pCount% GEQ %pLevel% goto :eof
for /d %%a in (%1*) do (
set p=%%a\
set p=!p:.\"=..\"!
echo exec md "%2\!p!"
md "%2\!p!"
call :mkdir "!p!" %2
)
endlocal
调用方式,如:cef "" c:\tmp3 或者 cef "c:\tmp1\" c:\tmp3
优化2
不使用递归调用,只使用一层循环
@echo off
cls
if [%2]==[] (echo [%time%] The destination folder is null. & goto :eof)
set dest=%2
set dest="%dest%" & set dest=%dest:"=%
if "%dest:~-1%" neq "\" (set dest=%dest%\)
set sour=%1
set sour="%sour%" & set sour=%sour:"=%
if "%sour%"=="" set sour=%cd%
if "%sour:~-1%" neq "\" (set sour=%sour%\)
setlocal enabledelayedexpansion
for /f "tokens=*" %%i in ('dir /s /b /ad "%sour%"') do (
::for /r %sour% %%i in (.) do (
set p=%%i
set p=!p:%sour%=!&set p=!p:\.=\!
echo exec md "%dest%!p!"
md "%dest%!p!"
echo.
)
endlocal
执行方式,如:cef "" c:\tmp3 或者 cef "c:\tmp1\" c:\tmp3
使用xcopy复制目录结构
示例:复制当前目录结构及子目录到上层目录的t1文件夹中
xcopy %cd% ..\t1 /C /E /K /T /Y
另外在给几个参考:
例如A目录下里有A1,A2,A3文件夹再分别有其余子目录,复制到B目录下的时候也需要存在A1,A2,A3文件夹及其余子目录,保留目录结构,目录里的文件在对应的目录下。
A:\A1\a2\new.txt
复制后:
B:\A1\a2\new.txt
1)仅复制以A为开头的目录结构
xcopy c:\xxx\a\A? d:\yyy\b /C /E /K /T /Y
2)复制以A为开头的目录结构及文件:
xcopy c:\xxx\a\A? d:\yyy\b /C /E /H /K /R /Y
=======================================================================================
bat批处理递归删除当前及子目录中的空文件夹
将以下代码复制保存至def.bat文件中,直接双击运行即可(不推荐使用)
@echo off
:deldir
setlocal enabledelayedexpansion
for /d %%a in (%1*) do (
set p="%%a\"
set p=!p:.\"=..\"!
rd !p! || ( call :deldir !p! & rd !p! )
)
优化:必须指定目标文件夹参数,调用方式:def.bat "c:\tmp"
@echo off
cls
:deldir
setlocal enabledelayedexpansion
if [%1] equ [] echo 未指定文件夹 & goto :eof
set fp=%1
set fp="%fp%" & set fp=%fp:"=%
if "%fp%" neq "" if "%fp:~-1%" neq "\" set fp=%fp%\
set fp="%fp%"
for /d %%a in (%fp%*) do (
set p="%%a"
set p=!p:.\"=..\"!
rd !p! || ( call :deldir !p! & rd !p!)
)
=======================================================================================