How to search for files with file names listed in a text file (DIR)?

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
tinfanide
Posts: 117
Joined: 05 Sep 2011 09:15

How to search for files with file names listed in a text file (DIR)?

#1 Post by tinfanide » 18 Sep 2019 03:07

A text file named 'source.txt' containing the file names to be searched for:

a.txt
b.txt
c.txt

I'd like to use 'DIR /B /S' command by referring to 'source.txt' to search for those files and copy those files to a new folder called 'destination'. Could anyone show me how to do that, please? Thank you!

Hackoo
Posts: 103
Joined: 15 Apr 2014 17:59

Re: How to search for files with file names listed in a text file (DIR)?

#2 Post by Hackoo » 21 Sep 2019 00:00

You can give a try with this batch script :

Code: Select all

@echo off
Title Search and copy from file written by Hackoo on 21/09/2019
set "Source=source.txt"
Set "SourceFolder=E:\Cam_Recorder" Rem You should modify this line to set your sourcefolder
set "DestinationFolder=E:\MyData\backupfiles" Rem You should modify this line to set your DestinationFolder
If Not Exist "%DestinationFolder%" MD "%DestinationFolder%"
set /a count=0
SETLOCAL enabledelayedexpansion
for /F "delims=" %%a in ('Type "%Source%"') do (
	For /f "delims=" %%F in ('dir /s /b "%SourceFolder%" ^|find /I "%%a"') Do (
			Set /a count+=1
			Set "File[!count!]=%%F"
	)		
)

For /L %%i in (1,1,%Count%) Do (
	set /a N=1
	echo Copying file [%%i] "!File[%%i]!"
	Call :MakeCopy "!File[%%i]!" "%DestinationFolder%"
)
pause & Exit
::*******************************************************
:MakeCopy <Source> <Destination>
Set Source="%~1"
Set Destination="%~2\"
set "Filename=%~n1"
set "Ext=%~x1"
echo N | Copy /-Y %Source% %Destination%>nul && goto :Loop
Exit /b
::*******************************************************
:Loop
if exist %Destination%%Filename%(%N%)%Ext% set /a N+=1
echo N | Copy /-Y %Source% %Destination%%Filename%(%N%)%Ext%>nul
Exit /b
::*******************************************************

Post Reply