Tutorial :Windows .BAT to move all directories matching mask from dir A to dir B


I want to write a .BAT file to move all sub-directories (whose name matches a mask) of C:\WINNT\Temp to H:\SOMEOTHERPLACE.

So if my mask is ABC* then the directories :

C:\WINNT\Temp\ABC1  C:\WINNT\Temp\ABC2  C:\WINNT\Temp\ABC3  

should be moved to


and everything else (including files, as opposed to directories, which match the mask) should not. I do want to move them and not copy.

Can anyone point me in the right direction ?


OK I've figured this out. If you write a movedirs.bat file containing the single line

for /d %%X in (%1) do move %%X %2\%%~nX   

And then run it (with argument 1 being the mask for the directories I want to move and argument 2 being the directory I wish to move the directories to) as

C:\>movedirs.bat C:\WINNT\Temp\ABC* H:\SOMEOTHERPLACE\  

It produces the effect I want.

The /d argument on the 'for' ensures that only directories are processed. The '~n' modifier on the %%X variable means that the original sub-directory name (as opposed to the entire path) is used as the target within the second command line argument.

Just for the sake of posterity in investigating this I did something similar with xcopy but then i would have had to get involved in deleting the source so for my purposes move works better but for the record here's the same idea wrapped around xcopy.

for /d %%X in (%1) do xcopy %%X %2\%%~nX /E /I  

To process directories with as well as without extensions, for example "C:\MyDir*.MyExt" above command will need a combined (filename+extension) modifier "~nx":

for /d %%W in (%1) do xcopy %%W %2\%%~nxW /E /F /R /Y /I  


[Comments are useless for structured answers so I'll repeat the comment here - with a couple of edits !]

Thanks for your answer but I've found that you can't use xcopy with a wildcard on the source. Or rather you can use wildcards but then you get only the directories being created without any content. So if you do this ...


... you'll get the the ABC1 directory copied to your current directory as you might reasonably expect but if you do this ...


... you'll get each directory name present in C:\WINNT\Temp appearing in your current directory but those directories will be empty ! Please tell me I'm wrong but that's what I find !

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »