user1113883
user1113883

Reputation:

Referring to the contents of a wildcard as a variable in a batch file

I am trying to write a batch file to copy a large number of files. I want to be able to take the file and move it to a specific folder based on its file name.

For example, I have a directory structure like this:

I would like to have a batch file that looks for all *.xyz files and copies them each to a folder according to their filename. So the above files would end up in the following directories.

File1.xyz gets copied to D:/FolderA/File1/File1.xyz

File2.xyz gets copied to D:/FolderA/File2/File2.xyz

File3.xyz gets copied to D:/FolderB/File3/File3.xyz

I know this should be possible using a FOR loop in a batch file, but I do not know how to take the text replaced by the wild card and use it as a variable (so I can create a folder with the same name.)

Upvotes: 0

Views: 730

Answers (1)

Aacini
Aacini

Reputation: 67216

for /R C:\ %%f in (*.xyz) do (
   if not exist D:%%~Pf%%~Nf md D:%%~Pf%%~Nf
   copy %%f D:%%~Pf%%~Nf/%%~NXf
)

The FOR variable modifiers give the info you need:

%%~D Expands to a Drive letter only.
%%~P Expands to a Path only, including an ending backslash.
%%~N Expands to the Name only.
%%~X Expands to the eXtension only.

Type FOR /? for further details.

Perhaps you need to copy the directory structure first with:

XCOPY C:\ D:\ /T

Upvotes: 1

Related Questions