I have a bunch of files:
CAR_003.dat
CAR_003.obj
CAR_004_prev0.png
CAR_004_prev1.png
CAR_004_tex0.tga
I need to rename them to:
CAR_002.dat
CAR_002.obj
CAR_003_prev0.png
CAR_003_prev1.png
CAR_003_tex0.tga
how I can do this with cmd on windows in a batch?
CodePudding user response:
You need to execute the following batch in the directory you want.
It will rename everything in the tree.
@ECHO off
SETLOCAL EnableDelayedExpansion
FOR /R %%f in (CAR*) DO (
FOR /F "usebackq tokens=1,2,* delims=_" %%m in ('%%~nxf') do (
SET filePath=%%~dpf
SET filePrefix=%%m_
SET /a fileNumber=1%%~nn-1001
SET fileNumber=000!fileNumber!
SET fileNumber=!fileNumber:~-3!
SET filePosfix=%%~no
SET fileExt=%%~xf
IF [!filePosfix!] EQU [] (
SET fileRest=%%~xf
) ELSE (
SET fileRest=_!filePosfix!!fileExt!
)
REM ECHO %%f
REM ECHO !filePath!!filePrefix!!fileNumber!!fileRest!
REM ECHO ~~~~~~~
MOVE "%%f" "!filePath!!filePrefix!!fileNumber!!fileRest!"
)
)
CodePudding user response:
Use a 0-9 loop for hundreds, for tens and for unit...
Order to compose a regex ([h][t][u]
) that can be used to isolate the looped file
Apply the subtraction and substring to get the target name
@echo off
cd /d "%~dp0"
setlocal enabledelayedexpansion
for /l %%h in (0,1,9)do for /l %%t in (0,1,9)do for /l %%u in (0,1,9
)do if exist .\"*_%%h%%t%%u*.*" call %:^) %%h%%t%%u "[%%h][%%t][%%u]"
%:^)
if /i "%~1" == "" (endlocal & goto :eOf)else set /a "_new=1%~1-1"
for /f "delims=" %%i in ('dir /b /a:-d .\* ^| findstr /er .*\_%~2.*
')do set "_name=%%~i" & call echo\ren "%%~i" "!_name:%~1=%_new:~-3%!"
exit /b
Obs.: Check if the rename commands are correctly composed on the output, and for effective execution remove the echo\
from the call echo\ren
command..
')do set "_name=%%~i" & call echo\ren "%%~i" "!_name:%~1=%_new:~-3%!"