实现一个关于拷贝递归目录下文件的批处理

时间:2021-10-30 11:33:38

需求:

某个文件夹A下存在若干子文件夹a1,a2,a3....和若干文件,子文件夹a1,a2,a3...下存在若干txt文件和xml文件,现要将A的子目录下的所有txt文件拷贝到A下的一个指定的新建的b文件夹中。

批处理:

 1 @echo off
 2 set inputPath=%cd%
 3 set outputPath=%cd%\Result
 4 echo %inputPath%
 5 echo %outputPath%
 6 if not exist "%outputPath%" md "%outputPath%"
 7 for /f "tokens=*" %%a in (
 8     'dir "%inputPath%\*.txt" /s /a-d /b'
 9     ) do (
10     copy "%%a" "%outputPath%\"
11 )
12 del "%outputPath%\mmlcmd.txt"
13 rem explorer "%outputPath%\"
14 pause

总结:

1、%cd%是系统变量,指示当前路径。

2、输出变量要加上%%,即%变量名%。

3、第6行代码刚开始是:if not exist %outputPath% md %outputPath%,当将该批处理文件放在桌面执行时总是报错('and' 不是内部或外部命令,也不是可运行的程序),所以,要规避这种情况,则需要再%变量名%上加上双引号,即"%变量名%"。

4、批处理中的for循环中有4个参数:/D,/R,/L,/F(DRLF不区分大小写),详细请在dos窗口中执行:for /? 来查看相关说明。