Home > Mobile >  How to correctly use multiple "for" commands
How to correctly use multiple "for" commands

Time:03-13

Ok, I've been at this for days now. And I've tried it step by step but there's always something going wrong.

What I'd like to do is this: I have my entire music collection on an external HDD. I'd like to run a batch file that will:

  • go into each category folder (category is the first letter of the artist name)
  • create a markdown file for the category listing each artist in the category
  • go into each artist folder
  • create a markdown file for the artist listing each album
  • go into each album folder
  • create a markdown file for the album listing each track
  • create an mp3 folder and move all the mp3s for that album into it

This is what I've tried (and many variations of...)

Make a temp list of categories..

for /f %%I in (.) do break > %%~nxI
dir /b /o:n /a:d > temp_categories.txt

For each category, make a category markdown file

for /f "delims=" %%C in (TEMP_categories.txt) do (
echo The %%C category >> %%C.md

Then I basically do the same thing to go into each artist folder and each album. When I get in the album folder, I add...

mkdir mp3
move [/Y | /-Y] *.mp3 mp3

It works up until it gets into the first album of the first artist in the first category. It adds the mp3 folder but doesn't move the files and it never goes to the next item.

I realize this is probably not the best code. But I only need it to work once. Otherwise I'll need to do everything manually.

CodePudding user response:

@ECHO OFF
SETLOCAL
rem The following setting for the source directory is a name
rem that I use for testing and deliberately includes spaces to make sure
rem that the process works using such names. These will need to be changed to suit your situation.

SET "sourcedir=u:\your files"

rem C ategories
FOR /d %%C IN ( "%sourcedir%\*") DO (
 CALL :validatecategory "%%~nxC"
 IF NOT DEFINED invalidcat (
  rem aR tists
  FOR /d %%R IN ( "%sourcedir%\%%~nxC\*") DO (
   ECHO %%~nxR>>"%%C\%%~nxC artists.md"
   rem A lbum
   FOR /d %%A IN ( "%sourcedir%\%%~nxC\%%~nxR\*") DO (
    ECHO %%~nxA>>"%%R\%%~nxR albums.md"
    MD "%%A\mp3" 2>nul
    rem T rack
    FOR %%T IN ( "%sourcedir%\%%~nxC\%%~nxR\%%~nxA\*.mp3") DO (
     ECHO %%~nxT>>"%%A\%%~nxA tracks.md"
     MOVE "%%T" "%%A\mp3" >nul
    )
   )
  )
 )
)
GOTO :EOF

:: Categories must be one character

:validatecategory
SET "invalidcat=%~1"
SET "invalidcat=%invalidcat:~1%"
GOTO :eof

Note that throughout, %%Q will have the full file/pathname and %%~nxQ the name where Q is C:Category R:Rtist A:Album T:Track.

Obviously, test against a test subtree first.

Note that I've assumed that the .mp3s are in the Album directory. If you move the .mp3s to an MP3 directory, then further runs will ignore them, so the tracks.md files should not be initialised to empty but the other .md files should be deleted on re-run.

  • Related