Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I need to change multiple files names based on their name.

I have files named like this.

001.mp3
002.mp3
003.mp3
004.mp3
005.mp3
...etc

I made some code to achieve my aim like this:

@echo off
for %%i in (*.mp3) do if %%~ni gtr 003 ren %%i %%~ni-new%%~xi

I have gotten successfully desired result like this:

001.mp3
002.mp3
003.mp3
004-new.mp3
005-new.mp3
...etc

But now I am trying something different like 'if between'.

For example:

@echo off
for %%i in (*.mp3) do 
if %%~ni between 001 && 003 ren %%i %%~ni-chapter-1%%~xi
if %%~ni between 004 && 006 ren %%i %%~ni-chapter-2%%~xi
if %%~ni between 007 && 020 ren %%i %%~ni-chapter-3%%~xi
if %%~ni between 021 && 030 ren %%i %%~ni-chapter-4%%~xi
if %%~ni between 031 && 045 ren %%i %%~ni-chapter-5%%~xi

so the desired result will be like this:

001-chapter-1.mp3
002-chapter-1.mp3
003-chapter-1.mp3
004-chapter-2.mp3
005-chapter-2.mp3
006-chapter-2.mp3
007-chapter-3.mp3
008-chapter-3.mp3
009-chapter-3.mp3
010-chapter-3.mp3
...etc

Please, help me to fix this code as demonstrated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
280 views
Welcome To Ask or Share your Answers For Others

1 Answer

I suppose you could use delayed expansion and remove the nested If statements too:

@Echo Off
SetLocal EnableDelayedExpansion
Set "i="
For /F "Delims=" %%A In ('Where .:???.mp3 2^>Nul')Do (
    If 1%%~nA Gtr 1000 Set "i=1"
    If 1%%~nA Gtr 1003 Set "i=2"
    If 1%%~nA Gtr 1006 Set "i=3"
    If 1%%~nA Gtr 1020 Set "i=4"
    If 1%%~nA Gtr 1030 Set "i=5"
    If 1%%~nA Gtr 1045 Set "i="
    If Defined i Ren "%%A" "%%~nA-chapter-!i!%%~xA"
)

In the example above, I have used the Where command to limit the returned metavariables to those with 3 character basenames. This will prevent cycling through any renamed files again, (as you were renaming them in the same directory with the same extension, which would still match your *.mp3 pattern).

Please note that this only filters .mp3 files with three characters, it does not make any determination that those characters are each integers. I'll leave you to decide if you wish to implement something like that yourself.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...