使用BAT查找并修改文件名
概要
使用BAT脚本实现:查找源文件“A_1.bin”,将其复制并改名为“B.bin”,当找不到或找到多个源文件“A.bin”时,报错并提醒如何处理
技术细节
@echo off
rem 设置延迟环境变量扩展
setlocal enabledelayedexpansion
title Modify The File Name
set "input=bbb"
set "input2=aaa_"
set "extension=.bin"
set "targetPath=./"
set /a var1+=0
set /a var2+=0
for /r "%targetPath%" %%C in (*%input2%*%extension%) do (
set "filename=%%~nC"
if "!filename:~0,14!"=="%input2%" (
set /a var1+=1
)
)
if !var1! leq 0 (
rem 换行
echo.
echo ------------------------------------------------------------------------------------------------------------------------------------------------
echo --ERROR--: Failed to find a file with the name format aaa_x.bin under the porgram directory.
echo --WARNING--: Please copy the file with the name format aaa_x.bin to the porgram directory.
echo ------------------------------------------------------------------------------------------------------------------------------------------------
rem 换行
echo.
pause
exit
)
if !var1! geq 2 (
rem 换行
echo.
echo ------------------------------------------------------------------------------------------------------------------------------------------------
echo --ERROR--: In the porgram directory, multiple files with the name format aaa_x.bin were found.
echo --WARNING--: Please ensure that there is only one file in the porgram directory with the name format of aaa_x.bin.
echo ------------------------------------------------------------------------------------------------------------------------------------------------
rem 换行
echo.
pause
exit
)
for /r "%targetPath%" %%B in (*%input2%*%extension%) do (
rem find aaa_x.bin
if "!filename:~0,14!"=="%input2%" (
set /a var2+=1
rem echo !var2!
rem echo Found file: %%B
if !var2! leq 1 (
rem bbb.bin
copy "%%B" %%~pB"bbb"%%~xB >nul
rem echo Modify filename to: %%~pbbb%%~xB
)
)
)
::pause