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: mp
优化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: mp3 或者 cef "c: mp1" c: mp3
优化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: mp3 或者 cef "c: mp1" c: mp3
参考:https://bbs.csdn.net/topics/370122833
使用xcopy复制目录结构
示例:复制当前目录结构及子目录到上层目录的t1文件夹中
xcopy %cd% .. 1 /C /E /K /T /Y
另外在给几个参考:
例如A目录下里有A1,A2,A3文件夹再分别有其余子目录,复制到B目录下的时候也需要存在A1,A2,A3文件夹及其余子目录,保留目录结构,目录里的文件在对应的目录下。
A:A1a2
ew.txt
复制后:
B:A1a2
ew.txt
1)仅复制以A为开头的目录结构
xcopy c:xxxaA? d:yyy /C /E /K /T /Y
2)复制以A为开头的目录结构及文件:
xcopy c:xxxaA? d:yyy /C /E /H /K /R /Y
参考:https://bbs.csdn.net/topics/392055120
=======================================================================================
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! ) )
出处:https://www.cnblogs.com/hhddd-1024/p/14275097.html
优化:必须指定目标文件夹参数,调用方式:def.bat "c: mp"
@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!) )
=======================================================================================