Batch file to read txt file with file names then search for that file and copy to folder

青春壹個敷衍的年華 提交于 2019-12-23 05:46:09

问题


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 in list.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 directories
  • SRC 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!