Windows Batch move to directory that may not exist
In a Windows batch file I am trying to move a file to a directory which may not currently exist. Because the directory is not there, when I do th开发者_开发知识库e move I see an error like:
The system cannot find the path specified
move c:\aaa\bbb\ccc\ddd\myfile.txt c:\aaa\111\222\333\444\mytext.txt
How can I easily create the path that I want to move to if it doesn't currently exist? For example here, directory 111 may not exist yet under aaa. I want the whole path structure to be created and then the file moved.
I had thought that it would just create the whole path for me as part of the move.Try:
md c:\aaa\111\222\333\444 2> nul
before your Move command.
md makes directories recursive, so if there are no parent directories to 444, it will keep creating hierarchically. The "2> nul" ensures that if you have the directory already, your command wouldnt error out.
If ROBOCOPY
is an option, it will create the folder structure if it doesn't exist.
Try this:
ROBOCOPY c:\aaa\bbb\ccc\ddd c:\aaa\111\222\333\444 mytext.txt /MOV
if not exist c:\aaa\111\222\333\444 md c:\aaa\111\222\333\444
Move c:\aaa\bbb\ccc\ddd\myfile.txt c:\aaa\111\222\333\444\mytext.txt
Continuing on Aruns answer:
md c:\aaa\111\222\333\444\mytext.txt
rd c:\aaa\111\222\333\444\mytext.txt
move c:\aaa\bbb\ccc\ddd\myfile.txt c:\aaa\111\222\333\444\mytext.txt
This creates a folder called mytext.txt
and its parents, and then deletes it, but not the parents.
More fun:
call :move_md "c:\aaa\bbb\ccc\ddd\myfile.txt" "c:\aaa\111\222\333\444\mytext.txt"
call :move_md "c:\aaa\bbb\ccc\ddd\myfile1.txt" "c:\aaa\111\222\333\444\mytext4.txt"
call :move_md "c:\aaa\bbb\ccc\ddd\myfile2.txt" "c:\aaa\111\222\333\444\mytext5.txt"
call :move_md "c:\aaa\bbb\ccc\ddd\myfile3.txt" "c:\aaa\111\222\333\444\mytext6.txt"
goto :eof
:move_md
md %2
rd %2
move %1 %2
goto :eof
Lets say you have the following directory structure.
C:\aaa\bbb\ccc\ddd
you want to create a directory called 111 under aaa, then 222 under 111, then 333 under 444 and so on
Window's cmd allows you to create a directory structure by providing multi level path
thus
md c:\aaa\111\222\333\444
will create all the directory till 444.
You may want to create the directory first and then perform the move
Continuing on johvs answer: I really love the idea, but if you have a larger number of files this will not work due to performance limitations. It took ~8.5s per file, and I have about 3mio files to move, which makes a total computation time of roughly ten months. With this option out of the field I have found this 2-step-solution - first copy the folder structure, and only then copy the files:
- xcopy C:\source C:\target /t /e
- move C:\source\aaa\bbb\ccc\ddd\myfile.txt C:\target\111\222\333\444\mytext.txt
This obviously has the disadvantage that it will create unnecessary folders, but for my purpose it's not an issue.
精彩评论