Search code examples
batch-fileffmpegbatch-rename

How to add suffix to duplicate filenames output by ffmpeg in Windows batch file?


I have written a script in Sony Vegas Pro that outputs an edit list of video files (E:\editlist.txt) of the following form, where the 2nd item is the start timecode and the 3rd item is the length:

E:\folder\file1a.mp4 16.8835333 17.5175
E:\folder\file2a.mp4 6.0393666 12.1454666
E:\folder\file3a.mp4 0 3.5368667
E:\folder\file3a.mp4 5.1344667 9.3033
E:\folder\file3a.mp4 12.1224623 19.483756

I have also cobbled together a Windows batch script that uses ffmpeg to trim those files and re-wrap them in a .mov container.

for /F "tokens=1,2,3 delims= " %%F in (E:\editlist.txt) do ffmpeg.exe -ss "%%G" -i "%%F" -c copy -t "%%H" "%%~dF%%~pF%%~nF.mov"

However because some files originate from the same source file (in this case, file3a.mp4), the trimmed files have duplicate names.

I would like to create a script that detects duplicates and adds an incremental single-digit suffix to the output file names, before the file extension. In this case the 5 output files should be file1a.mov, file2a.mov, file3a.mov, file3a1.mov and file3a2.mov.

I have had a go but I have no experience of writing Windows batch files, so the following effort fails and is probably very wrong, but hopefully it shows what I am trying to achieve (it was loosely based on an answer to this question):

for /F "tokens=1,2,3 delims= " %%F in (E:\editlist.txt)
    set counter=0
    if exist "%%~dF%%~pF%%~nF.mov" (
    set counter=%counter%+1
    do ffmpeg.exe -ss "%%G" -i "%%F" -c copy -t "%%H" "%%~dF%%~pF%%~nF%counter%.mov"
) else do ffmpeg.exe -ss "%%G" -i "%%F" -c copy -t "%%H" "%%~dF%%~pF%%~nF.mov"

I would greatly appreciate it if someone could help me get this working. Thanks!


Solution

  • Assuming the list file is sorted and the file names don't contain !, use set /a for calculations and enable the delayed expansion for variables:

    @echo off
    setlocal enableDelayedExpansion
    set prevfile=
    for /F "tokens=1,2,3 delims= " %%F in (E:\editlist.txt) do (
        if "%%F"=="!prevfile!" (
            if "!counter!"=="" (set counter=1) else (set /a counter+=1)
        ) else (
            set counter=
            set "prevfile=%%F"
        )
        ffmpeg -ss "%%G" -i "%%F" -c copy -t "%%H" "%%~dpnF!counter!.mov"
    )
    pause