问题
What I need is a batch file that reads partial file names in a txt file. Each file name is on its own line. Then it needs to search for that file in a specified folder (including sub folders) and if the file is found, copy the file to a folder on my desktop. I found a batch script that does almost exactly that, but my file names aren't a complete file name, only part of it with no extension, and this script searches for exact file names. I need to modify this script to search for files using only a part of the file name.
@echo off
REM (c) 2013 BY NEUTRON16 (http://www.sevenforums.com/member.php?u=3585)
CLS
TITLE Mass file finder by Neutron16
REM finds files in list.txt file and copies them to C:\your_files
REM CHECK FOR ADMIN RIGHTS
COPY /b/y NUL %WINDIR%\06CF2EB6-94E6-4a60-91D8-AB945AE8CF38 >NUL 2>&1
IF ERRORLEVEL 1 GOTO:NONADMIN
DEL %WINDIR%\06CF2EB6-94E6-4a60-91D8-AB945AE8CF38 >NUL 2>&1
:ADMIN
REM GOT ADMIN RIGHTS
COLOR 1F
ECHO Hi, %USERNAME%!
ECHO Please wait...
FOR /R "%~dp0" %%I IN (.) DO for /f "usebackq delims=" %%a in ("%~dp0list.txt") do echo d |xcopy "%%I\%%a" "C:\your_files" /e /i
COLOR 2F
ECHO.
ECHO (c) 2013 by Neutron16 (http://www.sevenforums.com/member.php?u=3585)
PAUSE
GOTO:EOF
:NONADMIN
REM NO ADMIN RIGHTS
COLOR 4F
ECHO.
ECHO PLEASE RUN AS ADMINISTRATOR
ECHO.
pause
GOTO:EOF
Can someone help me modify this?
回答1:
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET "DEST_DIR=%USERPROFILE%\Desktop\Folder"
SET "SEARCH_DIR=S:\Class"
FOR /F "tokens=*" %%a IN ('type %~dp0list.txt') DO (
FOR /R "%SEARCH_DIR%" %%f IN (*%%a*) DO (
SET "SRC=%%~dpf"
SET DEST=!SRC:%SEARCH_DIR%=%DEST_DIR%!
xcopy /S /I "%%~f" "!DEST!"
)
)
This is a modification of a single line (the FOR loop) in the script you posted.
- A recursive search is done for each line in
list.txt
. This is inefficient, but if you wanted efficiency, you probably wouldn't be using pure batch/CMD. - The matching is done as
*<pattern>*
, where <pattern> is a complete line inlist.txt
. tokens=*
: Regardless of delimiter, capture all text on each line as the content of the variable. (This is effectively the same as"delims="
.)/S
: don't process (or create) empty directoriesSRC
is used to allow substitution to build a destination path (which is a directory, not a file name—xcopy is designed for directories).
list.txt:
micro
pipeline
exhaust
回答2:
you can try this:
FOR /D /R "%~dp0" %%I IN (*) DO for /f "usebackq delims=" %%a in ("%~dp0list.txt") do xcopy "%%~I\%%~a" "C:\your_files" /e /i
For more help show list.txt
.
来源:https://stackoverflow.com/questions/17364141/batch-file-to-read-txt-file-with-file-names-then-search-for-that-file-and-copy-t