0

I intend to write a little DOS batch that creates m3u files for a given subdirectory structure containing sound files. The m3u file shall have the name '[Parent Directory].m3u' (where [Parent Directory] is replaced by the actual name of the parent dicrectory, of course).

My batch so far:

FOR /D /R %%I IN (\*.\*) DO (
IF EXIST "%%I\\*.mp3" (
    FOR %%* in ("%%I") do set X=%%~n*
    DIR /B "%%I\\*.mp3" > "%%I\\%X%.m3u"
    )
)

Well -- to put it short, it doesn't work as intended. The m3u files are created, but they have names like '.m3u' (Yepp, only the extension, no name at all).

The reason probably is that DOS does not allow to call a for loop within another for loop.

Hmmph -- is there any way to get the current directory name (and only the current one, not the whole path!) while working through an outer for loop?

Grateful thanks for any useful hint!

2

2 Answers 2

0

You should use your FOR construct to CD into each subdirectory and run your command from within the subdirectory.

Source For /R Loop through files (Recurse subfolders)

Loop through files (Recurse subfolders)

Syntax FOR /R [[drive:]path] %%parameter IN (set) DO command

Key

drive:path : The folder tree where the files are located.

set : A set of one or more files. Wildcards must be used. If (set) is a period character (.) then FOR will loop through every folder.

command : The command(s) to carry out, including any command-line parameters.

%%parameter : A replaceable parameter: in a batch file use %%G (on the command line %G)

This command walks down the folder tree starting at [drive:]path, and executes the DO statement against each matching file.

If the [drive:]path are not specified they will default to the current drive:path.

An Example

Change directory to each subfolder under C:\Work in turn:

FOR /R "C:\Work\" %%G in (.) DO (
    Pushd %%G
    Echo now in %%G
    Popd )
Echo "back home"

Try the following as your batch file

FOR /R %%G in (.) DO (
    Pushd %%G
    IF EXIST "*.mp3" (
        DIR /B *.mp3 > "%CD%.m3u"
    )
    Popd
)

Notes:

  • %CD% is the current directory.
0

The reason your output names have only an extension is because you attempt to expand the X variable in the same block that sets it. Normal expansion occurs when the statement is parsed, and the entire block is parsed at once. So you get the value of X that existed before the loop was entered (not defined).

That problem can be solved using delayed expansion (setlocal enableDelayedExpansion at top, and !X! instead of %X%. But there is a better way that is even simpler than DavidPostill's solution.

The following will work directly on the command line - no batch script required.

for /r %F in (.) do @if exist "%F\*.mp3" dir /b *.mp3 >"%F\%~nxF.mp3"

Double the percents if you use the command in a batch script.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .