Hi so I have a following problem
Suppose you have some Windows folder structure with different files (all files have different names but may have the same extension):
dirA
subDirA
file1.png
file2.dds
file3.jpeg
dirB
subDirB
subSubDirB
file4.tiff
some_txt.txt
test.cfg
final.docx
And now you copy all the files recursively to some other directory:
file1.png
file2.dds
file3.jpeg
file4.tiff
some_txt.txt
test.cfg
final.docx
And now what I want to do is to copy all these files back to their original folders (note that the previous folders and files are still there, I just copied them) and overwrite previous files. In reality there is a lot of files so it is not an option to manipulate them by hand.
Is there some simple way to do this or I'd better write custom program/script to do this?
Answer
I would usually prefer a batch solution for something like this:
@echo off
set "orig=C:\Original\Directory"
set "dir=C:\Some\Directory"
for /r "%orig%" %%A in (*) do (
if exist "%dir%\%%~nxA" copy /y "%dir%\%%~nxA" "%%A"
)
The orig
variable will be the top-folder you want to loop recursively through (i.e. dirA
or dirB
from your example block - or if they share a folder you can go as high as you want as long as you're confident about there not being duplicate names). The dir
variable will be that folder you had previously copied all of the files to.
for /r
loops through all files rooted in a directory (meaning orig
and all of its subfolders); for each iteration it sets the full path and extension of the file as %%A
, then within the loop we see if %%~nxA
(the file reduced to its name and extension) exists in our dir
location; if it does exist, we copy that file from dir
over itself in the orig
location. That's it. If you'd like to generate a log file to check I usually recommend using robocopy and have it output everything from the loop into a text file, which would look like this:
@echo off
set "orig=C:\Original\Directory"
set "dir=C:\Some\Directory"
setlocal enabledelayedexpansion
for /r "%orig%" %%A in (*) do (
set "path=%%~dpA"
if exist "%dir%\%%~nxA" robocopy "%dir%" "!path:~0,-1!" "%%~nxA"
)>>"%dir%\Return Files.txt"
Only tricky difference there is to enable delayed expansion so you can clip the trailing \
from the %%~dpA
.
No comments:
Post a Comment