使用方法:
copy_files_by_prefix.bat [目标目录] [结果目录] [文件名前缀] [可选参数:文件包含内容]
@echo off
chcp 65001 >nul
setlocal enabledelayedexpansion:: Check parameters
if "%~3"=="" (echo Usage: %~nx0 [SourceDir] [TargetDir] [FilePrefix] [OptionalContent]echo Example: %~nx0 "C:\source" "D:\backup" "doc_" "123"goto :eof
):: Get parameters
set "source_dir=%~1"
set "target_dir=%~2"
set "prefix=%~3"
set "keyword=%~4":: Check if source directory exists
if not exist "%source_dir%\" (echo Error: Source directory does not exist - "%source_dir%"goto :eof
):: Create target directory if not exists
if not exist "%target_dir%\" (mkdir "%target_dir%"echo Created target directory: "%target_dir%"
):: Initialize counter
set file_count=0:: Scan and copy files
echo Scanning "%source_dir%\" for files starting with "%prefix%"...for /r "%source_dir%" %%f in ("%prefix%*") do (set "file_path=%%f"set "file_name=%%~nxf"if defined keyword (findstr /C:"!keyword!" "%%f" >nul 2>nulif errorlevel 1 (rem echo Skipping: %%f) else (set /a file_count+=1echo Copying: "!file_path!" to "%target_dir%\!file_name!"copy "!file_path!" "%target_dir%\" >nul)) else (set /a file_count+=1echo Copying: "!file_path!" to "%target_dir%\!file_name!"copy "!file_path!" "%target_dir%\" >nul)
):: Show results
echo.
echo Operation completed!
echo Copied %file_count% files to "%target_dir%"
pause