在cmd和批处理中用数字序列重命名多个文件

Rename multiple files with a sequence of numbers in cmd and batch

这是我在这个美丽的网站上提出的第一个问题。 正如您可能在标题中读到的那样,我想重命名可变数量的文件,在 cmd 和批处理文件中使用一系列数字,序列在增加,就像这样(1、2、3、4、5, 6、7、8、9、10...)。 例如:

Test.txt 应该变成 1.txt

Another.txt 应该变成 2.txt

等等,都是自动的。

我的想法是设置一个像set /a number=1这样的变量,然后通过循环向它添加这样的+1 set number="%number%+1",每次都重命名,但是自从我重命名后就不可能了ren 的文件 命令它立即重命名。

谁能帮我提供一个cmd和批处理文件版本?

提前致谢

这应该适合你。

set /a Index=1

setlocal enabledelayedexpansion

for /r %%i in (*.txt) do ( 
    rename "%%i" "!Index!.txt"
    set /a Index+=1
)

使用上述代码创建一个批处理文件,并将其运行 放在您的 .txt 文件所在的文件夹中。

如果要附加“0”使其成为 2 位数字。您可以尝试添加 if else 语句,如下所示。

set /a Index=1

setlocal enabledelayedexpansion

for /r %%i in (*.txt) do ( 
    rem if number is less than 10, append 9 to file name
    if !Index! lss 10 (
        rename "%%i" 0"!Index!.txt"
    ) else (
        rename "%%i" "!Index!.txt"
    )
    
    set /a Index+=1
)