Batch file to copy files from a file contents

2019-07-12 14:52发布

I have a master file (File1.txt) where some names are maintained in the contents. I have to find all the files which has those kind of names (wild cards) in a folder and move them to a different folder using batch file program.

Eg : File1.txt has contents

  abcd
  efgh

now in the folder say c:\temp\Source i have files like

12abcd34.asc
56efgh78.asc
testing.asc

I have to move only those 2 files to a folder say c:\temp\Target.

Here's my code, but it gives error saying i*.* is unexpected at this time. Can you please help .

@Echo Off
title Test move files
set dir1=C:\temp\Source
dir %dir1%
Echo Directory Changed
FOR /f "eol=; delims=, " %i in (file1.txt) do move /y "*%i*.*" Target

1条回答
该账号已被封号
2楼-- · 2019-07-12 15:35

Here you go....

This is what the directory structure is when I start...

C:\Temp>tree /f
Folder PATH listing for volume OS
Volume serial number is XXXX-XXXX
C:.
│   file1.txt
│   run.bat
│
├───Source
│       12abcd34.asc
│       56efgh78.asc
│       testing.asc
│
└───Target

This is the run.bat that I will run later .. includes the bug fixes...

C:\Temp>copy run.bat con
@Echo Off

title Test move files

set dir1=Source

dir %dir1%

Echo Directory Changed

FOR /f "eol=; delims=, " %%i in (file1.txt) do move /y "%dir1%\*%%i*.*" Target
        1 file(s) copied.

Now I run the batch file ...

C:\Temp>run.bat
 Volume in drive C is OS
 Volume Serial Number is XXXX-XXXX

 Directory of C:\Temp

19/07/2012  00:03    <DIR>          .
19/07/2012  00:03    <DIR>          ..
18/07/2012  23:59                 0 12abcd34.asc
18/07/2012  23:59                 0 56efgh78.asc
18/07/2012  23:59                 0 testing.asc
               3 File(s)              0 bytes
               2 Dir(s)  41,653,194,752 bytes free
Directory Changed
C:\Temp\Source\12abcd34.asc
        1 file(s) moved.
C:\Temp\Source\56efgh78.asc
        1 file(s) moved.

Now this is the final directory structure ... so you can see that it is working ...

C:\Temp>tree /f
Folder PATH listing for volume OS
Volume serial number is XXXX-XXXX
C:.
│   file1.txt
│   run.bat
│
├───Source
│       testing.asc
│
└───Target
        12abcd34.asc
        56efgh78.asc

Here is the for loop you need...

FOR /f "eol=; delims=, " %%i in (file1.txt) do move /y "%dir1%\*%%i*.*" Target

Changes:

[1] within FOR you use %%i not %i.
[2] You need this format:

%dir1%  <-- Where
\       <-- path delimiter
*       <-- starts with anything
%%i     <-- contains what you want to search
*.*     <-- ends with anything

Hope this helps.

查看更多
登录 后发表回答