批处理:将具有相同部分名称的文件从子文件夹复制到另一个

时间:2016-11-08 15:44:51

标签: batch-file for-loop subdirectory xcopy

我想从已知数量的子文件夹中复制具有共同名称一部分的文件。我试过这段代码:

@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

1 个答案:

答案 0 :(得分:0)

根据您迄今为止提供的内容,也许这就是您的意图:

@ECHO OFF

REM Make sure script directory is current
IF /I NOT "%CD%\"=="%~dp0" PUSHD "%~dp0" 2>NUL||EXIT/B

REM Make sure source files exist
FOR %%A IN ("subFoldersList.txt" "formatList.txt") DO IF NOT EXIST %%A EXIT/B

REM Delete aFolder if it exists
IF EXIST "aFolder\" RD/S/Q "aFolder"

REM Create aFolder
MD "aFolder"

REM Copy the files from the subfolders inside of bFolder to aFolder    
FOR /F "USEBACKQ DELIMS=" %%A IN ("subFoldersList.txt") DO (
    IF EXIST "bFolder\%%A\" (PUSHD "bFolder\%%A"
        FOR /F "USEBACKQ DELIMS=" %%B IN ("%~dp0formatList.txt") DO (
            IF EXIST "commonPart.%%B" (
                IF NOT EXIST "%~dp0aFolder\commonPart.%%B" (
                    COPY "commonPart.%%B" "%~dp0aFolder")))
        POPD))