Wildcard Directory Copy in DOS Batch
Moving lots of directories using DOS Batch and wild cards
This is great for those hideous clean up jobs where you have masses of sub-directories and you want to move a large subset of them somewhere else.
I had a directory and it was full of sub-directories looking like this :
2009-12-01 07:33 111-y-888
2009-12-01 07:32 123-x-456
2009-12-01 07:32 123-y-456
2009-12-01 07:32 125-y-456
2009-12-01 07:33 876-x-342
2009-12-01 07:33 999-x-123
There were thousands of these things and I only wanted to remove the ones that had an ‘x’ in the middle.
No problem I thought XCopy will do this. Well strange to say but if you want to use wild cards – and clearly I did – XCopy won’t drill down and copy the contents of the director you’re copying. You can use the /E flag and get an empty directory copied but not the actual contents.
Weirdo DOS Batch arguments !
Weirdo DOS Batch arguments to the rescue ! I wrote a one line .BAT file like this :
for /d %%X in (%1) do move %%X %2\%%~nX
I called that movedirs.bat and then to move all the ‘x’ directories from E:\ABC to E:\XYZ I called it like this
movedirs.bat E:\ABC\*x* E:\XYZ
which uses a for loop to process each directory which matches the wildcard individually and uses xcopy on each sub-directory within the for loop.
The gory details
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.
So good I wrote it twice
Just to be up front this post is based on a stackoverflow question I posed and then answered myself. It seemed too useful to just be there so I recycled it for my blog.