Home > database >  using for loop to copy selected files in directory and subdirectories to new directory with the same
using for loop to copy selected files in directory and subdirectories to new directory with the same

Time:12-22

for /r "C:\Users\bui\Desktop\Annotation Traing Package\test1" %i in (*03.json)  do copy "%i" "C:\Users\bui\Desktop\Annotation Traing Package\test2"

i want to copy all 03.json files from test1 to test2 but in test1 folder, there are subfolders, and in those subfolders also have 03.json files. With for loop i cant loop through subfolders and copy 03.json files in it, but i also want to copy those subfolders from test1 to test2 with those 03.jon files in it. is there possible way to do it?

i tried using xcopy to copy those subfolders first then use for loop but no use, bc they copy all files to "C:\Users\bui\Desktop\Annotation Traing Package\test2"

CodePudding user response:

try this.

@echo off

rem Set the source and destination directories
set source_directory = "C:\Users\bui\Desktop\Annotation Traing Package\test1"
set destination_directory = "C:\Users\bui\Desktop\Annotation Traing Package\test2"

rem Set the name of the file to search for
set filename = 03.json

rem Iterate through all the subfolders in the source directory
for /D %%A in (%source_directory%\*) do (

    rem Check if the file exists in the current subfolder
    if exist %source_directory%\%%A\%filename% (
    
        rem Copy the file and the subfolder to the destination directory
        xcopy %source_directory%\%%A            
  • Related