Wally Walters
Wally Walters

Reputation: 75

Import subroutine code into FOR loop

I have a small batch file designed to read file names from a folder containing audio tracks and output them into a playlist. The program works well enough, but I had trouble getting the "write track names" code into the FOR loop -- I had to leave it as a subroutine or the batch file would exited prematurely. Is there any way to move those three lines into the FOR loop?

@echo off
%~d1
cd %1
for %%* in (.) do set FOLDER="%%~nx*"
set PLAYLIST=%FOLDER%.m3u
for /f "tokens=*" %%g in ('dir /b *.flac *.mp3') do (
  call :WRITE_TRACK_NAMES "%%g"
  )
goto :CHECKOUT
:WRITE_TRACK_NAMES
  set "TRACK=%~nx1"
  echo %TRACK%  >> %PLAYLIST%
  goto :EOF
:CHECKOUT
  exit /b

Upvotes: 0

Views: 78

Answers (1)

michael_heath
michael_heath

Reputation: 5372

@echo off
setlocal

@rem Change drive and path.
cd /d %1

for /d %%A in (.) do set "FOLDER=%%~nxA"

@rem If in drive root, . is returned.
if "%FOLDER%" == "." exit /b 1

@rem Create m3u file or erase m3u file content.
2> "%FOLDER%.m3u" echo.

@rem Find and sort audio files and add filename to m3u file.
for /f "tokens=*" %%A in ('dir /b *.flac *.mp3 ^| sort') do >> "%FOLDER%.m3u" echo(%%~nxA

exit /b
  • Use setlocal to prevent the cd and variables affecting the global scope of the CMD process.
  • Using /d argument with cd allows switching drive when changing the path.
  • Using sort as you are using more then 1 file pattern with the dir command.
  • Advise not using %%* as a for variable name as %* is all arguments of the script or called label.
  • Removed PLAYLIST name as has no good use.
  • Create or erase m3u file to prevent duplicating filenames with appending writes.

Upvotes: 1

Related Questions