Windows bat file to rename multiple files with cus

2019-09-20 13:20发布

问题:

I have multiple folders with multiple files in each of them. The file names are as following: static-string-1.wav static-string-2.wav .... static-string-10.wav ... static-string-99.wav static-string-100.wav ... and so on. The static string remains same but the number before .wav changes from 1 - 999. Now the problem is if I want to play this on any media player or want to join all the files, windows will sort like 1,10,100,2,20,200 not 1,2,3,4,5,6,7,8,9,10 which messes up the playback. So to fix this, I have to rename each file from static-string-1.wav to static-string-0001.wav and so on. Currently, I am doing a dir command to an output file and then I copy the file list in excel from where I do some playing around with concatenate and text to columns and come up with two columns of old name and new name which I then again convert to a .bat file with and run it. The bat file has multiple rows with individual rename commands something like this:


@echo off
rename <oldname1> <newname0001>
rename <oldname2> <newname0002>
.
..
exit

It is getting the work done but I know there is and easier and more efficient way to use for loops. I saw few example and previous answers but they dont have a similar requirement as me. Any help will be appreciated.

回答1:

Below is a significant improvement to Clayton's answer

  • Only numbers less than 100 need be modified
  • The script automatically works with any static prefix. See How does the Windows RENAME command interpret wildcards? for an explanation of how this works.
  • The script reports any file names that could not be renamed
@echo off
setlocal enableDelayedExpansion
for /l %%N in (1 1 99) do (
  set "n=00%%N"
  for %%F in (*-%%N.wav) do ren "%%F" *-!n:~-3!.* || >&2 echo ERROR: Unable to rename "%%F"
)

Or, you could grab my JREPL.BAT regular expression renaming utility and simply use:

jren "-(\d{1,2})(?=\.wav$)" "'-'+lpad($1,'000')" /j


回答2:

Leading zeros can be added and (later) truncated if not needed. This question is a possible duplicate, but I don't like how files are sorted like that either.

Delaying the expansion allows b to change within the for loop instead of being static (haha puns) throughout the whole program. Therefore you can increment b each loop and rename the files. This is a simple example:

@echo off
setlocal ENABLEDELAYEDEXPANSION
for /l %%a in (1,1,99) do (
    set b=00%%a
    rename static-string-%%a.wav static-string-!b:~-2!.wav
)

This should work. Contact me if you need more help