Maxim
Maxim

Reputation: 11

Batch renaming files by removing specific characters before file extension?

I am having a set of files in folders and sub-folders where I want to remove specific characters from files like below:

adjust_the_m.2_retainer_zh-cn.dita
assert_physical_presence_en-us.dita
back_up_the_server_configuration_es.dita
backplane_cable_routing_fr-fr.dita

I want to rename them as below:

adjust_the_m.2_retainer.dita
assert_physical_presence.dita
back_up_the_server_configuration.dita
backplane_cable_routing.dita

I want this in Command Prompt Batch.bat file.

Upvotes: 1

Views: 710

Answers (2)

Maxim
Maxim

Reputation: 11

Now final code is as below:

@echo off
setlocal enabledelayedexpansion
for /r %%a in (*.dita *.ditamap *.ditaval) do call :process "%%~dpna" "%%~xa"
goto :eof

:process
set "file=%~1"
for %%b in (%file:_= %) do set last=_%%b
rem echo %last%
set "file=!file:%last%=!"
move "%~1%~2" "%file%%~2"
echo %file%%~2

Thanks for your help @Stephan!

Upvotes: 0

Stephan
Stephan

Reputation: 56180

You want to remove the last part (delimited with _) of the filename?
Take the name without extension (%%~dpna), get the last part, remove it from the filename (set variable substring replacement) and add the extension (%%~xa)

@echo off

setlocal enabledelayedexpansion
for /r %%a in (*.dita) do call :process "%%~dpna" "%%~xa"
goto :eof

:process
set "file=%~1"
for %%b in (%file:_= %) do set last=_%%b
set "file=!file:%last%=!"
move "%~1%~2" "%file%%~2"

Upvotes: 1

Related Questions