【发布时间】:2016-11-08 15:44:50
【问题描述】:
我想从已知数量的子文件夹中复制具有部分共同姓名的文件。我试过这段代码:
@Echo Off
rem Check if the aFolder exists and delete it if it exists
IF EXIST "%~dp0\aFolder" (
rd /s /q "%~dp0\aFolder"
)
rem Create a new aFolder
mkdir "%~dp0\aFolder"
rem Copy the files from the subfolders inside of bFolder to aFolder
For /F "tokens=1" %%A in (%~dp0\subFoldersList.txt) do (
For /F "tokens=1" %%B in (%~dp0\formatList.txt) do (
pushd "%~dp0\bFolder\%%A"
For %%C in (%%AcommonPart.%%B) do xcopy %%C "%~dp0\aFolder"
)
)
代码使用两个包含不同数据的 txt 文件。 在 subFoldersList.txt 中:
subFolder1
subFolder2
subFolder3
在formatList.txt中:
xls
xlsx
xlsm
检查循环不运行的代码,我不知道为什么。
编辑:
我使用的文件夹骨架是这样的:
rootFolder
|->aFolder
||-->subFolder1
|||--->subFolder1commomPart.xlsx (for example)
|||--->subFolder1other1Part.xlsm (for example)
|||--->subFolder1other2Part.xls (for example)
||-->subFolder2
|||--->subFolder1commomPart.xlsm (for example)
|||--->subFolder1other1Part.xlsx (for example)
|||--->subFolder1other2Part.xls (for example)
||-->subFolder3
|||--->subFolder1commomPart.xls (for example)
|||--->subFolder1other1Part.xlsm (for example)
|||--->subFolder1other2Part.xlsx (for example)
|->bFolder
|->subFoldersList.txt
|->formatList.txt
|->Other Stuff
我想得到这个结果:
rootFolder
|->aFolder
||-->subFolder1
|||--->subFolder1commomPart.xlsx (for example)
|||--->subFolder1other1Part.xlsm (for example)
|||--->subFolder1other2Part.xls (for example)
||-->subFolder2
|||--->subFolder1commomPart.xlsm (for example)
|||--->subFolder1other1Part.xlsx (for example)
|||--->subFolder1other2Part.xls (for example)
||-->subFolder3
|||--->subFolder1commomPart.xls (for example)
|||--->subFolder1other1Part.xlsm (for example)
|||--->subFolder1other2Part.xlsx (for example)
|->bFolder
||--->subFolder1commomPart.xlsx (for example)
||--->subFolder1commomPart.xlsm (for example)
||--->subFolder1commomPart.xls (for example)
|->subFoldersList.txt
|->formatList.txt
|->Other Stuff
【问题讨论】:
-
%~dp0 已经有一个尾随反斜杠,删除你在它后面添加的那些!
-
我觉得
For %%C in (%%AcommonPart.%%B) do xcopy %%C "%~dp0\aFolder"应该改成For %%C in ("commonPart.%%B") do xcopy "%%~C" "%~dp0\aFolder\",因为pushd已经改成子文件夹%%A了;还要注意改进的引用,%%~C中的~和目标处的尾随反斜杠。您还应该将tokens=1更改为delims=。请向我们展示一些文件名示例... -
您也必须发出
POPD。 -
@Compo 谢谢。我之前已经使用了反斜杠,并且代码运行良好。
-
@Tilan04,这只是建议,尝试添加一行
ECHO %~dp0,您会发现虽然您的方式可能在错误之前对您有用。我在下面的回答,它进行了其他更改,也显示了我的建议。
标签: batch-file for-loop subdirectory xcopy