简体   繁体   中英

Copy files in multiple sub-directories to another directory with matching sub-directory names

I can't seem to figure out a good way to do what the title states. I need to move all files found in various sub-directories to another directory with matching sub-directory names. The code that I have been working with is:

@echo off
IF EXIST path.txt del /f path.txt
:: Above line for test only

for /f %%i in ('DIR /a:d /b "C:\ProgramData\Test\WTM\Source"') do (
    echo %%i >>path.txt
)
::Pull sub-directory name from working folder

for /f "delims=" %%a in ('DIR /s /a-d /b "C:\ProgramData\Test\WTM\Source"') do (
    for /F %%b in (path.txt) do (
        move /y "%%a" "C:\ProgramData\Test\WTM\Destination\%%b\*.*"
    )
)
PAUSE

What I am trying to do is pull the sub-directory names (as a few may be missing from the destination from time to time), find all of the files to move in the source directory, then move the files using the previously pulled sub-directory names to the destination directory under the respective sub-directory names. So pulling

C:\ProgramData\Test\WTM\Source\123\123.txt,
C:\ProgramData\Test\WTM\Source\456\9681.txt,
C:\ProgramData\Test\WTM\Source\789\1941.txt,
etc...

and moving those files to

C:\ProgramData\Test\WTM\Destination\123\123.txt,
C:\ProgramData\Test\WTM\Destination\456\9681.txt,
C:\ProgramData\Test\WTM\Destination\789\1941.txt,
etc...

My code never runs correctly and errors vary depending on what I change, but usually I can't get %%b to be passed as the sub-directory name and not %b , or I can get it to work using a parameter (setting set %%i = path and then substituting %%b for %path% ), but then it only copies files to the last sub-directory and not all of them due to how I am utilizing the set command there.

I need some pointers, I just can't seem to get it to do what I want. Any and all pointers are appreciated! Thanks a ton!

I know you have this tagged as batch, but as @FlorianStraub mentioned, you can use robocopy to mirror one directory to another:

robocopy *.* "C:\src" "C:\dest" /E

To break this command down:

  • *.* says to copy all files
  • "C:\\src" is your source directory, while
  • "C:\\dest" is your destination directory.
  • The /E flag at the end says to copy all folders recursively, and include empty folders.

Try running robocopy /? from your command line to see more options.

If your dest directory has extra files that you want you get rid of, use the /MIR flag to 1-to-1 mirror your source directory into the destination. That is, it'll delete any file in the destination that don't also exist within the source.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM