0

I have a large set of files (45,000+) in a pretty complex folder structure. I extracted a subset of ~13,000 files and their paths (relative to the root folder) that I want to copy with the original folder path.

Although I've searched thoroughly, I couldn't find a way, with xcopy or robocopy, to do what I want. I could easily create a batch file with one copy command for each entry in my list. However, I couldn't find any x/robocopy switch or combinations of switches that will generate the folder path in the target from my source file, e.g:

xcopy dir1\dir2\dir3\file.txt copy_folder /<some switches>

or

xcopy dir1\dir2\dir3\file.txt copy_folder\dir1\dir2\dir3\file.txt /<some switches>

I would want it to create the path dir1\dir2\dir3 if it does not exist under the folder copy_folder and place a copy of file.txt there. I understand that, on Linux cp --parent does exactly that.

Any suggestion on the best way to achieve this is most welcome!

1 Answer 1

1

XCOPY will create the folders if they do not exist, but it first prompts asking if the destination is a File or Directory.

So you can pipe the F response to the XCOPY command so that the command does not pause.

for /f "delims=" %%F in (yourList.txt) do echo f 2>nul | xcopy /y "%%~F" "copyFolder\%%~F"

The /Y option is used in case you have duplicates in your list - you don't want the XCOPY command to prompt asking if you want to overwrite.

The redirection of stderr to nul is needed in case the path does exist, in which case the right side may complete before the left, causing the left to print out the following error message to stderr - The process tried to write to a nonexistent pipe. The redirection hides the unwanted error message.

Another option is to first create the destination path prior to doing the XCOPY. Simply redirect stderr to null to avoid seeing an error message if the path already exists.

for /f "delims=" %%F in (yourList.txt) do (
  md "copyFolder%%~pF" 2>nul
  xcopy /y "%%~F" "copyFolder\%%~F"
)

With either solution, if the path in your list includes a drive letter, then you will need to use
"copyFolder%%~pnxF" instead of "copyFolder\%%~F". Note that the ~p modifier includes the leading \.

2
  • Yes, it works! Good learning for me, as I didn't realize you could pipe a keyboard response this way. One thing I appreciate some clarification on: you explained >nul, but what does the 2 just before mean? Thanks!
    – mrgou
    Commented May 23, 2019 at 7:06
  • This is just ... bizarre. No wonder people hate MS.
    – Ira Baxter
    Commented May 13, 2020 at 23:40

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .