Search code examples
batch-filexcopy

Batch file to copy and rename files from multiple directories


I have previously searched for an answer for my question, however nothing to this point has specifically answered it. See: Using xcopy to copy files from several directories to one directory, and Batch file to copy files from one folder to another folder .

Within one directory (Data) I have specifically named multiple directories e.g. (SIAE02203) that contain generically named .JPEG files (plot.jpeg). I hope to create a batch file that is able to go through each directory, locate, copy AND rename the plot.jpeg file with the parent's folder name.

So plot.jpeg becomes SIAE02203-plot.jpeg.

The structure of the directories looks like: Data\SIAE02203\plots\plot.jpeg. I hope to copy the renamed file to Data\Output.

Would this be at all possible?


Solution

  • Here is a short batch code for this task:

    @echo off
    pushd "C:\Temp\Data"
    if not exist "Output\*" md Output
    for /D %%D in (*) do (
        if /I not "%%D" == "Output" (
            for %%J in ("%%D\plots\*.jpeg") do (
                copy /B /Y "%%~fJ" "Output\%%D-%%~nxJ" >nul
            )
        )
    )
    popd
    

    Specify in second line the path to directory Data.

    The batch file creates first the directory Output if not already existing.

    Next command FOR is used to process more commands on each subdirectory of directory Data. The subdirectory Output is skipped using an IF condition.

    The inner FOR searches for each subdirectory found by outer FOR in subdirectory plots like SIAE02203\plots for *.jpeg files and copies all found JPEG files to directory Output.

    The success message of command COPY is redirected to device NUL to suppress it.

    Input example structure for directory C:\Temp\Data:

    • SIAE02203
      • plots
        • backup
          • backup_plot.jpeg
        • image.jpg
        • plot.jpeg
      • images
        • image.jpg
        • plot.jpeg
      • photo.jpeg
    • TIAE03208
      • plots
        • another.jpeg
        • ignored.jpg
        • plot.jpeg

    Contents of C:\Temp\Data after batch execution:

    • Output

      • SIAE02203-plot.jpeg
      • TIAE03208-another.jpeg
      • TIAE03208-plot.jpeg
    • SIAE02203

      • plots
        • backup
          • backup_plot.jpeg
        • image.jpg
        • plot.jpeg
      • images
        • image.jpg
        • plot.jpeg
      • photo.jpeg
    • TIAE03208
      • plots
        • another.jpeg
        • ignored.jpg
        • plot.jpeg

    For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

    • copy /?
    • echo /?
    • for /?
    • if /?
    • popd /?
    • pushd /?

    See also the Microsoft article about Using command redirection operators for an explanation of >nul.