Command Prompt/Batch - rename multiple files with sequential numbering

放肆的年华 提交于 2020-05-14 22:04:06

问题


Lets say I have multiple files

filename.a.txt
filename.b.txt
filename.c.txt

I want to run a batch file that targets all .txt files and rename them to whatever I have set into my custom %filename% var + give them numbers so it would end up into something like:

filename.1.txt
filename.2.txt
filename.3.txt

So far I have wrote this:

set filename=FileTitle
for /r %%i in (*.txt) do call ren %%i %filename%.txt

And it works, but problem is that it just picks up first .txt file and gives it the FileTitle filename and that's it. I can't figure how to rename all .txt files in a batch and give them unique sequential number as a prefix/suffix/custom var to the outputed %filename%.txt so something like e.g. %filename%-%uniquesuffix%.txt. So I need to set some kind of variable that gives each file a unique number e.g. from 1-99 in alphabet order (default order that cmd prompt picked files up).

I did search other answers, but they show only how to add global/same prefix to renamed files.


回答1:


@echo off
setlocal EnableDelayedExpansion

set filename=FileTitle
set suffix=100
for /F "delims=" %%i in ('dir /B *.txt') do (
   set /A suffix+=1
   ren "%%i" "%filename%-!suffix:~1!.txt"
)

This code renames the files in the form you requested. Note that the numeric suffix have two digits in order to preserve the original alphabet order of the files. If "natural" 1-99 numbers were used, then the order in that cmd prompt show the files is changed in this way: 1.txt 10.txt 11.txt ... 19.txt 2.txt 20.txt 21.txt ... 29.txt 3.txt ... (alphabet order, NOT numeric one). If may be more than 99 files, just add another zero in set suffix=100 command to generate a three-digits suffix.

Note also that your plain for command may process some files twice or more times depending on the site where the renamed files will be placed in the original files list. To avoid this problem use a for /F command over a dir /B *.txt one. This method first get a list of all files, and then execute the renames over such a static list.

To process all files under current folder (that is the purpose of your /r switch in for command), just add a /S switch in the dir command.




回答2:


You could use the following code to do the job.

@echo off
pushd %~dp0
setlocal EnableDelayedExpansion

set filename=FileTitle
set Num=1
for /r %%i in (*.txt) do (
    ren "%%i" "%filename%.!Num!.txt"
    set /a Num+=1
)

You can look at https://ss64.com/nt/delayedexpansion.html to see how the code works.



来源:https://stackoverflow.com/questions/42863483/command-prompt-batch-rename-multiple-files-with-sequential-numbering

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!