batch-filereplaceffmpeg

str_replace %%~na File Name In Batch File


I want to replace the current file name inside a batch file

for %%a in ("*.mp4") do  ffmpeg -i "%%~a" -vf "drawtext=text=%%~na:fontfile='C\:\\Users\\harin\\Desktop\\test\\Fonts\\Glamy Sunrise.ttf':fontcolor=black:fontsize=54:x=20:y=50" -b:v 1M -r 60 -b:a 144k  -crf 17 "C:\Users\harin\Desktop\test\in\Working\1\%%~na.mp4"

Need to replace drawtext=text=%%~na with some thing like this drawtext=text=str_replace(array('-','_'),array(' ',''),%%~na)

how can i do this... thx


Solution

  • The modification of the file name can be done using delayed variable expansion:

    @echo off
    setlocal EnableExtensions DisableDelayedExpansion
    for %%I in (*.mp4) do (
        set "FullFileName=%%I"
        set "OnlyFileName=%%~nI"
        setlocal EnableDelayedExpansion
        set "OnlyFileName=!OnlyFileName:_=!"
        set "OnlyFileName=!OnlyFileName:-= !"
        ffmpeg.exe -i "!FullFileName!" -vf "drawtext=text=!OnlyFileName!:fontfile='C\:\\Users\\harin\\Desktop\\test\\Fonts\\Glamy Sunrise.ttf':fontcolor=black:fontsize=54:x=20:y=50" -b:v 1M -r 60 -b:a 144k -crf 17 "C:\Users\harin\Desktop\test\in\Working\1\!OnlyFileName!.mp4"
        endlocal
    )
    endlocal
    

    It is assumed that the current directory on batch file execution is not the directory C:\Users\harin\Desktop\test\in\Working\1 as in this case a modification of the FOR command line should be done to process a list of file names loaded first into memory of cmd.exe before running the commands inside the body of FOR. This can be achieved by using as third line:

    for /F "eol=| delims=" %%I in ('dir *.mp4 /A-D-L /B 2^>nul') do (
    

    The batch file code can be optimized to the following code if there is never an MP4 file in the current directory containing one or more exclamation marks in file name.

    @echo off
    setlocal EnableExtensions EnableDelayedExpansion
    for %%I in (*.mp4) do (
        set "FileName=%%~nI"
        set "FileName=!FileName:_=!"
        set "FileName=!FileName:-= !"
        ffmpeg.exe -i "%%I" -vf "drawtext=text=!FileName!:fontfile='C\:\\Users\\harin\\Desktop\\test\\Fonts\\Glamy Sunrise.ttf':fontcolor=black:fontsize=54:x=20:y=50" -b:v 1M -r 60 -b:a 144k -crf 17 "C:\Users\harin\Desktop\test\in\Working\1\!FileName!.mp4"
    )
    endlocal
    

    To understand the commands used and how they work, open a command prompt window, execute there the following commands, and read the displayed help pages for each command, entirely and carefully.

    Note: It would be most efficient to specify ffmpeg.exe with its fully qualified file name enclosed in " if the full path contains a space or one of these characters &()[]{}^=;!'+,`~ as in this case cmd.exe would not need to search for the file ffmpeg.exe on each *.mp4 file using the environment variables PATH and PATHEXT.