How can I recursivly copy a directory structure and only copy the files in the bottom tier (Windows Batch)

StackOverflow https://stackoverflow.com/questions/8430615

  •  11-03-2021
  •  | 
  •  

Question

My directory structure looks like this;

folder1
  folder2 (thousands of folders like this)
    folder3
        someImage.jpeg
        someDoc.doc
        folder4 (optional folder)
           someImage.jpeg
           someDoc.doc

I want the script to copy the folder 2s which contain folder 4s maintaining the folder structure but only copying the files in folder 4. Like this;

folder1
  folder2 (thousands of folders like this)
    folder3
      folder4 (optional folder)
        someImage.jpeg
        someDoc.doc

I've got a simple for loop which can identify the folders which contain folder 4 and then Robocopy the files to some directory. I can't figure out how to copy the entire folder structure whilst skipping the files at folder 3.

Was it helpful?

Solution

There is an option in the xcopy command that creates the directory tree.

  /T           Creates directory structure, but does not copy files. Does not
               include empty directories or subdirectories. /T /E includes
               empty directories and subdirectories.

Do it first and then merely copy the files inside folder 4s.

OTHER TIPS

as @Andryi pointed out in his comment, you can't unequivocally determine whether or not a folder is the lowest possible in the tree structure. So you must decide in advance which one you want to consider low enough to start copying. Suppose you decide it's folder fourth in the structure. In that case, use this code to get you started.

@echo off
for /d %%a in (*.*) do (
  echo  %%a
  for /d %%b in (%%a\*.*) do (
    echo  %%b
    for /d %%c in (%%b\*.*) do (
      echo  %%c
      for /d %%d in (%%c\*.*) do (
        echo  %%d
        for    %%f in (%%d\*.*) do (
          echo  %%f
        )
      )
    )
  )
)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top