2017-06-30 45 views
1

重命名文件我想要重命名initialy命名一些像这样的文件:批次:通过数字填充用零

KIT0_rawinput_descriptors.m => KIT00_rawinput_descriptors.m 
KIT0_rawinput_estimation.m => KIT00_rawinput_estimation.m 
KIT0_rawinput_label_kp.m 
KIT1_rawinput_descriptors.m => KIT01_rawinput_descriptors.m 
KIT1_rawinput_estimation.m 
KIT1_rawinput_label_kp.m 

我写了这个批处理文件,但它不工作,它说,有一个与另一个文件找不到相同的名称或文件!我没有明白这一点!请帮我

setlocal enableextensions enabledelayedexpansion 
set idx="xx" 
for /l %%x in (0, 1, 1) do (
    Set "Pattern=KIT%%x_" 
    Set "Replace=KIT0%%x_" 
    for /r %%# in (*!Pattern!*) do (
     Set "File=%%~nx#" 
     echo "!File!" 
     rem Ren "%%#" "!File:%Pattern%=%Replace%!" 
     ) 
    ) 
endlocal 
+0

难道你不能简单地用'KIT0'替换/替换'KIT' – Compo

回答

1

虽然使用的是延迟扩展您的%Replace%已经在一个区域需要延迟扩展,所以你用不同的方法需要两次:

setlocal enableextensions enabledelayedexpansion 
set idx="xx" 
for /l %%x in (0, 1, 1) do (
    Set "Pattern=KIT%%x_" 
    Set "Replace=KIT0%%x_" 
    for /r %%# in (*!Pattern!*) do (
     Set "File=%%~nx#" 
     echo "!File!" 
     Call Echo Ren "%%#" "%%File:!Pattern!=!Replace!%%" 
     ) 
    ) 
endlocal 

如果输出看起来OK删除Call和Ren之间的回声。

+0

我对批处理文件并不熟悉! 当你说“一个需要延迟扩展的区域”是因为“for/r %%#in”吗?如果不是那么因为什么? 延迟扩展是使用双重百分比“%%”完成的?这个扩展符号“%”和这个“!”之间有什么区别? 非常感谢你的帮助和你的回答 – Yazan

+0

简而言之:这是cmd分析批处理的方式。首先评估括号内的区域变量(代码块)。如果**在代码块中设置了一个变量**,那么它的新值只能通过延迟扩展来检索。在你的情况下,'Pattern'和'Replace'在代码块中设置,替换命令本身需要延迟扩展来强制实际值以及变量File。伪调用是一种较老的方法,用于双edelayed扩展。有关如何cmd分析batche的详细信息,请参阅[本问答](https://stackoverflow.com/questions/4094699) – LotPings

+0

感谢您的帮助和解释 – Yazan