Page 1 of 1

Parsing exclamation marks in filenames of %%i

Posted: 11 Dec 2023 06:54
by RuinedElf
Hiya! Got a bit of a question. Been trying to figure out how to parse exclamation marks in filenames when using a variable, as the subject head says.

Currently, I have a batch file that will do what I want it to do (FFMPEG audio extraction as MP3 from MP4 into separate folder). However, I'm stumbling over getting it to recognize exclamation marks in the filename. Please see below:

Code: Select all

@echo off
setlocal EnableDelayedExpansion

set "inputDirectory=X:\Media\YouTube\music_videos\"
set "bitrate=192k"

REM Loop through all MP4 files in the input directory and its subfolders
for /r "%inputDirectory%" %%i in (*.mp4) do (
    set "inputFile=%%i"
    set "outputPath=%%~dpi"
    set "outputFile=!outputPath:_videos=!%%~nxi.mp3"

    REM Ensure the output directory for the current file exists
    if not exist "!outputPath:_videos=!\.." mkdir "!outputPath:_videos=!\.."

    REM Check if the output file already exists
    if not exist "!outputFile!" (
	
    REM Execute FFMPEG command to convert MP4 to MP3 with specified quality
        ffmpeg -i "!inputFile!" -vn -acodec mp3 -ab !bitrate! "!outputFile!"
    ) else (
        echo Output file for "!inputFile!" already exists. Skipping.
	)
)
echo Conversion completed.
pause
As you can see, I have EnableDelayedExpansion since I'm using the !! variables in the loop. My understanding is that this completely locks me out of using exclamation marks in my filenames, but I have to use the !! variables due to the loop. Is this correct? Still very much a newbie! Any help would be much appreciated, thank you!

Re: Parsing exclamation marks in filenames of %%i

Posted: 12 Dec 2023 07:15
by jeb
Hi RuinedElf ,

your problem is, that expansion of FOR-variables is only safe when DelayedExpansion is disabled.
But working with variables is only safe when DelayedExpansion is enabled.

You can solve this by toggling delayed expansion.

Code: Select all

REM Loop through all MP4 files in the input directory and its subfolders
SETLOCAL DisabledDelayedExpansion
for /r "%inputDirectory%" %%i in (*.mp4) do (
    set "inputFile=%%i"
    set "outputPath=%%~dpi"
    set "outputFile=!outputPath:_videos=!%%~nxi.mp3"
    SETLOCAL EnabledDelayedExpansion
    ....
    ENDLOCAL
)