3

I need to convert all MP4 files in my subdirectories to MKV. So I wrote this script:

@ECHO OFF
SET oldName=
SET newName=

FOR /r %%A IN (*.mp4) DO (
    SET oldName=%%A
    SET newName=%%A
    CALL :MAKEMKV
)

:MAKEMKV
SET newName=%newName:mp4=mkv%
IF NOT EXIST %newName% (
    START /B /WAIT ffmpeg -i "%oldName%" -map 0 -map -0:s -codec copy "%newName%"
)

The problem is that only first file in folder is converted and then it exits. But I use for do loop. So I could not get why it exits.

My structure is:

/FOLDER
../A/filea.mp4
../B/fileb.mp4
../C/filec.mp4

When I run above program I get only converted filea.mp4 to filea.mkv and script exits.
The other files fileb.mp4 and filec.mp4 are not converted by the batch file.

What I am missing?

Mofi
  • 46,139
  • 17
  • 80
  • 143
Igor Petev
  • 597
  • 2
  • 6
  • 24

2 Answers2

2

Using modifiers (see for /? or call /?), this is basically a one-liner:

@ECHO OFF
FOR /r %%A IN (*.mp4) DO (
  if not exist "%~dpnA.mkv" (
    START /B /WAIT ffmpeg -i "%%~A" -map 0 -map -0:s -codec copy "%%~dpnA.mkv"
  )
)

(writen as multiline for better readability)

Haven't worked with ffmpeg, but probably you don't need thes start command:

@ECHO OFF
FOR /r %%A IN (*.mp4) DO (
  if not exist "%~dpnA.mkv" (
    ffmpeg -i "%%~A" -map 0 -map -0:s -codec copy "%%~dpnA.mkv" && del "%%~A"
  )
)

Added also code to delete the original mp4, if conversion was successful.

Stephan
  • 53,940
  • 10
  • 58
  • 91
2

Run in a command prompt window for /? and read the help output on several pages.

There is no real need for a batch file as this task can be done from command line with:

for /R %I in (*.mp4) do @if not exist "%~dpnI.mkv" ffmpeg.exe -i "%I" -map 0 -map -0:s -codec copy "%~dpnI.mkv" && del "%%I"

The same command line from within a batch file:

@echo off
for /R %%I in (*.mp4) do if not exist "%%~dpnI.mkv" ffmpeg.exe -i "%%I" -map 0 -map -0:s -codec copy "%%~dpnI.mkv" && del "%%I"

I can't answer why your batch file fails because of not knowing the folder structure with real folder names and the real file names. But Stephan is right with IF NOT EXIST %newName% ( failing in case of file name with full path contains a space or one of these characters &()[]{}^=;!'+,`~ because of not being enclosed in double quotes.

Note: && del "%%I" results in deleting the just converted *.mp4 file if conversion was successful and ffmpeg.exe exited with 0 being usually the exit/return code for success. See also Single line with multiple commands using Windows batch file.

And read also Where does GOTO :EOF return to? in case of ever writing once again a batch file with a subroutine. The batch file in question miss a goto :EOF or exit /B after the FOR loop to avoid a fall through to the subroutine code on FOR having finished. That would not be a problem here, but is in general not right.

Mofi
  • 46,139
  • 17
  • 80
  • 143