[Solved] Batch file to copy and rename files from multiple directories


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.

1

solved Batch file to copy and rename files from multiple directories