How to copy file and folder structure using xcopy from a text file

batch-filexcopy

I have a text file containing a list of files and folders. What I want to do is use xcopy to replicate what is written in the text file. My text file looks like this:

"C:\FOLDER"  
"C:\FOLDER\FILE1.TXT"
"C:\FOLDER\FILE2.TXT"
"C:\FOLDER\FOLDER2"
"C:\FOLDER\FOLDER2\FILE3.TXT"

For a given output directory "C:\OUTPUT" I would like to replicate the entire structure, so:

"C:\OUTPUT\FOLDER"  
"C:\OUTPUT\FOLDER\FILE1.TXT"
"C:\OUTPUT\FOLDER\FILE2.TXT"
"C:\OUTPUT\FOLDER\FOLDER2"
"C:\OUTPUT\FOLDER\FOLDER2\FILE3.TXT"

How can I accomplish this? So far I have written a for loop that reads in each line of the file, but it copies all files if the line is a folder. What I want to do is only copy and create the files and folders that are mentioned in the text file.

@echo off
for /f "delims=] tokens=1*" %%a in (textfile.txt) do (
   XCOPY /S /E %%a "C:\OUTPUT"
)

Am I on the right track?

Thank you and best regards,

Andrew

Best Answer

Yes, you are close. Just need to use the existing path as the appended destination path.

Update

@echo off
for /f "delims=" %%A in (textfile.txt) do if exist "%%~fA\*" (
    md "C:\Output\%%~pA"
    copy /y "%%~fA" "C:\Output\%%~pnxA"
)

Original

If %%A = "C:\Folder\Folder2\File3.txt", then %%~pA = Folder\Folder2

@echo off
for /f "delims=" %%A in (textfile.txt) do (
    md "C:\Output\%%~pA"
    if not exist "%%~fA\*" echo f | xcopy "%%~fA" "C:\Output\%%~pnxA" /y
)

The if not exist "%%~fA\*" makes sure to only copy the entry if it is not a directory. See Reference for more Techniques and Comments

Type in for /? at the command line to view a list of the variable modifiers. %%~A will remove the surrounding quotations (if any) from the variable.

Post about xcopy prompting issue. and fix #2.

Alternate Setup, since you most likely will not need the xcopy abilities.

@echo off
for /f "delims=" %%A in (textfile.txt) do (
    md "C:\Output\%%~pA"
    if not exist "%%~fA\*" copy /y "%%~fA" "C:\Output\%%~pnxA"
)
Related Topic