Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
283 views
in Technique[技术] by (71.8m points)

batch file - Using IF statements with multiple conditions

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...