通过在文件扩展名前删除特定字符来批量重命名文件?

时间:2017-11-17 08:04:30

标签: batch-file file-rename batch-rename

我在文件夹和子文件夹中有一组文件,我想从下面的文件中删除特定字符:

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

我想将它们重命名如下:

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

我想在命令提示符Batch.bat文件中使用它。

2 个答案:

答案 0 :(得分:1)

您想删除文件名的最后一部分(用_分隔)? 取名称不带扩展名(%%~dpna),获取最后一部分,从文件名中删除它(set变量子串替换)并添加扩展名(%%~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"

答案 1 :(得分:0)

现在最终代码如下:

@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

感谢您的帮助@Stephan!