Search code examples
windowsbatch-filexcopy

Copy files matching string(s) in a text file out of many subfolders with folder structure to another destination folder


I have a lot of image files in a folder structure like this:

/Foldername1 (hohe Auflösung)/PictureRANDOMNAME1-FB.jpg
/Foldername1 (hohe Auflösung)/PictureRANDOMNAME2-FB.jpg
[...]
/Foldername2 (hohe Auflösung)/PictureRANDOMNAME1-SW.jpg
/Foldername2 (hohe Auflösung)/PictureRANDOMNAME2-SW.jpg
[...]
/Foldername3 (hohe Auflösung)/PictureRANDOMNAME1-SP.jpg
/Foldername3 (hohe Auflösung)/PictureRANDOMNAME2-SP.jpg
[...]

Now I have a filelist.txt with a list of some of these image files, like this:

PictureRANDOMNAME1, PictureRANDOMNAME3, [...]

I would like to copy all images matching the string(s) in the text file list out of all subfolders to a new destination (not moving them) while keeping the folder structure.

Maybe I need a batch file that I just copy into the main folder with all the subfolders, together with a filelist.txt, execute it and get the same folder structure but only with the wanted files on another destination.

Special about this might be the spaces in the paths and the umlauts.

Sorry for my bad english. I honestly tried my best. Maybe some native speaker could help editing to be more understandable.


Solution

  • @echo off
    setlocal
    :: This copies the tree structure from sourcedir to destdir
    xcopy /t /e sourcedir destdir
    :: This reads the filenames and copies the required files
    for /f "delims=" %%a in (filelist.txt) do (
     for %%b in (%%a) do xcopy /s /e sourcedir\%%b* destdir
    )
    

    %%a acquires the lines from the file. Since each line is comma-separated, %%b will execute xcopy on each name on the line.

    You could add >nul to the end of the xcopy lines to suppress reporting if you like.

    Please note that / indicates a switch in winbatch - \ is the directory-separator.

    This procedure is untested. I suggest you try it against a small dummy subdirectory tree to verify it before relying on it for your live data.