Reputation: 43
This is the first time I actually use batch.
I have multiple files I want to merge with ffmpeg:
3 - Making Your First Pickup Class.f303.webm
3 - Making Your First Pickup Class.f251.webm
I am trying to do it using the following script:
for %%g in (*.webm) do (
ffmpeg -y -i %%~ng.f251.webm -i %%~ng.f303.webm -c copy -map 0:v:0 -map 1:a:0 -shortest %%~ng.mp4
)
cmd /k
The problem is that I need to remove the last TWO extensions for this to work correctly.
E.g.: I am getting 3 - Making Your First Pickup Class.f303.f251.webm
:
In short, I need what will look like %%~n(%~ng)
Upvotes: 2
Views: 1801
Reputation: 49097
Here is one solution:
@echo off
setlocal EnableDelayedExpansion
for %%G in (*.f303.webm) do (
set "FileName=%%~nG"
set "FileName=!FileName:~0,-5!"
ffmpeg.exe -y -i "!FileName!.f251.webm" -i "!FileName!.f303.webm" -c copy -map 0:v:0 -map 1:a:0 -shortest "!FileName!.mp4"
)
endlocal
The FOR loop does not search anymore for any file with extension .webm
, but instead just for one of the two files to merge. This avoids the double merge.
The string .f303
is removed by assigning file name without .webm
to an environment variable which is copied to same variable without the last 5 characters.
It is necessary to use delayed expansion because the environment variable FileName
is modified within a block defined with (
...)
.
Another method would be using a subroutine as demonstrated below:
@echo off
for %%G in (*.f303.webm) do call :Merge "%%~nG"
goto :EOF
:Merge
ffmpeg.exe -y -i "%~n1.f251.webm" -i "%~n1.f303.webm" -c copy -map 0:v:0 -map 1:a:0 -shortest "%~n1.mp4"
exit /B
Double quotes are necessary around all file names because of the spaces in the *.webm file names.
%~n1
is replaced by file name of first argument without file extension which means the substring of first argument from first character after last backslash (if present at all) to last character before last dot in string being interpreted as separator between file name and file extension.
For the command processor it does not matter in most cases if first argument is really the name of an existing file or an existing folder on determining "file/folder" name (%~n1
), "file" extension (%~x1
) and "file/folder" path with drive (%~dp1
).
The file or folder must be found only if the string of first argument is incomplete to determine the string. For example if just name of a file with file extension but without drive and path is passed as first argument and %~dp1
is used somewhere, the command processor must find the file or folder to determine drive and path for this file/folder.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
call /?
explains briefly usage of a subroutine as well as %~n1
.echo /?
endlocal /?
exit /?
for /?
goto /?
set /?
setlocal /?
Upvotes: 2