Search code examples
batch-filefile-renamebatch-rename

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.


Solution

  • 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!