Search code examples
batch-filecopysubdirectory

Copy all sub-folders with a specified name into a merged folder using .bat


I would like to copy all sub-folders (including the contents of these folders) with the name "PHASE 1" and merge their contents in another location.

Example files in my current directory:

Folder 1\PHASE 1\test1.pdf
Folder 2\PHASE 1\test2.pdf
Folder 3\PHASE 1\test3.pdf

I would like these to be copied into a single directory like so:

MASTER FOLDER\PHASE 1
>test1.pdf
>test2.pdf
>test3.pdf

I would like to create a loop to repeat this process for PHASE 2, PHASE 3, etc.

This is all I have tried with no success:

for /r "%cd%" %%x in ("PHASE 1") do copy /y "%%x" ""%cd%"\MASTER FOLDER"

Solution

  • for /f "delims=" %%A in ('dir /a:d /b /s "PHASE *"') do (
        xcopy /y "%%~A" "MASTER FOLDER\%%~nxA\"
    )
    

    Look at for /? and you may see:

    (set) Specifies a set of one or more files. Wildcards may be used.

    PHASE 1 is a folder name which seems to be an invalid value for (set).

    Instead of for /r, for /f using the dir command could get the directory paths which match a wildcard pattern.

    The code above uses dir to get the directories with /a:d, recurse with /s and returns in bare format with /b.

    The for /f option of delims= causes each path to be returned, without spliting into tokens.

    xcopy copies each matching directory path into the MASTER FOLDER directory.

    If you need to ensure that the wildcard of the pattern PHASE * matches digits, then dir could be piped to findstr to filter the returned paths.