Reputation: 135
I have a folder structure like:
-MainDir
-f0
-f0
-f0
-a.txt
-b.txt
-c.txt
-f1
-f1
-f1
-aa.txt
-bb.txt
-cc.txt
If you see above my files are in 3rd folder in terms of hierarchy. Now my requirement is to be able to copy only the main folder and it's files to another location. For example: output for above structure should be as following:
-MainDir
-f0
-a.txt
-b.txt
-c.txt
-f1
-aa.txt
-bb.txt
-cc.txt
but when I try using XCOPY, all the folders get copied as it is. So I am trying to figure out a way to achieve my target folder structure as shown above
Upvotes: 0
Views: 2087
Reputation: 34909
This is a quite easy task using xcopy
together with a for /D
loop, given that the three sub-directories in each hierarchy branch are equally named (like f0\f0\f0
and f1\f1\f1
):
rem // Loop through immediate sub-sirectories of main directory:
for /D %%I in ("D:\MainDir\*") do (
rem /* Build path to files into second sub-directory (though there are no files);
rem the third sub-directory and its contents is regarded due to the `/S` option;
rem the copy destination directory then receives the whole contents of the
rem second source sub-directory, including the third source sub-directory: */
xcopy /S /I "%%~I\%%~nxI\*.*" "D:\CopyDir"
)
Upvotes: 1
Reputation: 3264
The following will loop the directories under main, find all files, and put them all in the top most sub directory in destination as you're looking for:
CMD Script:
@(SETLOCAL
ECHO OFF
SET "_MainDir=C:\Main\Dir"
SET "_DestDir=%Temp%\Destination\Main\Dir"
)
FOR /D %%A in (
%_MainDir%\*
) DO (
IF NOT EXIST "%_DestDir%\%%~nxA" MD "%_DestDir%\%%~nxA"
FOR /F %%a IN ('
DIR /A-D /S /B "%%~fA\*"
') DO (
ECHO Copying: "%%~fa"
ECHO To: "%_DestDir%\%%~nxA\%%~nxa"
COPY /B /V /Y "%%~fa" "%_DestDir%\%%~nxA\%%~nxa"
)
)
Upvotes: 1