Reputation: 13
Hi I'm trying to replace _C which are at the end of each file name. I used @echo off REN . ?????????.*
This works fine but the file name width could differ so what else can I do to select only the last 2 characters and rename it?
Upvotes: 0
Views: 3268
Reputation: 319
You can use enhanced expanding of environment variable, e.g.:
%PATH:~0,-2%
would extract all but the last 2 characters of the PATH variable. For more details, check help of set command.
And you can use FOR command to apply it on every file. Don't forget to use delayed expansion (using exclamation instead of percent) inside for cycle.
FOR /F %I IN ('dir *.* /B') DO (
set a=%~nI
ren %I !a:~0,-2!%~xI
)
Check help of FOR command for more details.
Update: I revised the FOR cycle and created usable batch code (including explanation comments), which works also with long filenames containing spaces. Just put this into .bat file a then run this batch inside directory, where you need to rename files. Note: The percent needs to be doubled when used inside batch file.
@echo off
rem use extensions and delayed expansion
setlocal ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION
FOR /F "tokens=*" %%I IN ('dir *.* /B') DO (
rem Skip this batch
if "%0" NEQ "%%I" (
rem show renamed file
echo %%I
rem set A to filename without extension
set A=%%~nI
rem rename file to A minus last two characters with appended extension (which includes period)
ren "%%I" "!A:~0,-2!%%~xI"
))
Upvotes: 2