251

How do you convert an entire directory/folder with ffmpeg via command line or with a batch script?

bryc
  • 7,107
  • 6
  • 34
  • 50
Eugene
  • 9,015
  • 18
  • 58
  • 86

27 Answers27

396

For Linux and macOS this can be done in one line, using parameter expansion to change the filename extension of the output file:

for i in *.avi; do ffmpeg -i "$i" "${i%.*}.mp4"; done
Matthias Braun
  • 24,493
  • 16
  • 114
  • 144
llogan
  • 87,794
  • 21
  • 166
  • 190
  • 3
    This is perfect, thank you! Here's full command that ended up working great for me: for i in *.avi; do ffmpeg -i "$i" -c:a aac -b:a 128k -c:v libx264 -crf 20 "${i%.avi}.mp4"; done – Phil Kulak Apr 28 '17 at 03:29
  • I am getting `i was unexpected at this time.` error in cmd, windows 10. I used following line: `for i in *.mp3; do ffmpeg -i "$i" -map_metadata -1 -c:v copy -c:a copy "${i%.mp3}.mp3"; done` – Junaid May 17 '17 at 07:13
  • 1
    @Junaid 1) Make sure to use a different name for the output file than the input, or output to another directory, because `ffmpeg` can't input and output to the same file. 2) I'm not sure if Bash commands work on Windows 10 natively. Maybe I should add to the answer that it is targeted towards systems that can natively use Bash such as Linux and macOS. lxs provided an Windows answer for this question. – llogan May 17 '17 at 17:25
  • 5
    Awesome answer. Works with filenames with spaces too! – wisbucky Jan 04 '19 at 22:14
  • Install git on Windows, it comes with bash shell (git-bash.exe). – Audrius Meskauskas May 20 '19 at 12:00
  • 2
    This should be the top answer. Admittedly, the explanation for why {$i%.*} is not simple, but if you can put that aside and just "use it" you can quickly modify to suit. For example, I converted hundreds of .mp4's (with filenames having spaces and special characters) to a smaller format using: for i in *.mp4; do ffmpeg -i "$i" -s 512x288 -c:a copy "${i%.*}.m4v"; done – Tony M Jun 26 '19 at 15:56
  • It works great. On my case, upgrading from FLV to MP4, a plain copy thru thousands of files, this is the full command: `for i in *.flv; do ffmpeg -i "$i" -codec copy "${i%.*}.mp4"; done` – Luis H Cabrejo Jul 30 '19 at 07:35
  • 2
    To take it one step further, you could use [Bash parameter substitution](https://www.cyberciti.biz/tips/bash-shell-parameter-substitution-2.html) if you would like to replace the string "x265" with "x264" if you're transcoding from H.265 to H.264 which is a common use case. `for f in *.mkv; do ffmpeg -i "$f" -map 0 -movflags faststart -c:v libx264 -c:a copy -c:s copy "${f/x265/x264}"; done` – Travis Runyard Dec 06 '19 at 16:36
  • Thank you, your solution is perfect. This slightly modified command worked for me `for i in *.MOV; do ffmpeg -i "$i" -vcodec libx265 -crf 20 "${i%.MOV}.mp4"; done` – Giorgi Aptsiauri Jul 18 '20 at 19:01
216

Previous answer will only create 1 output file called out.mov. To make a separate output file for each old movie, try this.

for i in *.avi;
  do name=`echo "$i" | cut -d'.' -f1`
  echo "$name"
  ffmpeg -i "$i" "${name}.mov"
done
tripleee
  • 139,311
  • 24
  • 207
  • 268
Isaac
  • 2,241
  • 1
  • 12
  • 7
90

And on Windows:

FOR /F "tokens=*" %G IN ('dir /b *.flac') DO ffmpeg -i "%G" -acodec mp3 "%~nG.mp3"
lxs
  • 5,737
  • 3
  • 18
  • 19
  • 21
    if you run this command in a batch (.bat) file you need to double the % signs => %% – hB0 May 17 '15 at 14:24
  • 1
    Any idea how to run this command but copy to a new file that includes the original file's metadata? – Barryman9000 Feb 26 '16 at 17:53
  • @Barryman9000 this was a long time ago but I think there's an output file option you could pass – lxs Mar 21 '16 at 15:00
  • @lxs thanks for the follow up. I ended up doing it with Powershell by changing the new file's name to be the original file's date created http://stackoverflow.com/a/35671099/197472 – Barryman9000 Mar 21 '16 at 23:08
  • Used it for removing metadata. But it is giving me Access denied error. So I changed output file name with an extra space to make it new file. `FOR /F "tokens=*" %G IN ('dir /b *.mp3') DO ffmpeg -i "%G" -map_metadata -1 -c:v copy -c:a copy "%~nG .mp3"` – Junaid May 17 '17 at 07:27
  • 2
    For **PowerShell**: `Get-ChildItem *.ogg -recurse | % { ffmpeg.exe -i $_.FullName -map_metadata -1 -c:v copy -c:a copy ("NewPath" + "\" +$_.Name) } ` Where `NewPath` = new directory path. – Junaid Nov 30 '18 at 19:55
  • Why not `FOR %G IN (*.flac) DO ...`? – Thomas Weller Jan 07 '21 at 19:48
33

For Windows:

Here I'm Converting all the (.mp4) files to (.mp3) files.
Just open cmd, goto the desired folder and type the command.

Shortcut: (optional)
1. Goto the folder where your (.mp4) files are present
2. Press Shift and Left click and Choose "Open PowerShell Window Here"
or "Open Command Prompt Window Here"
3. Type "cmd" [NOTE: Skip this step if it directly opens cmd instead of PowerShell]
4. Run the command

for %i in (*.mp4) do ffmpeg -i "%i" "%~ni.mp3"

If you want to put this into a batch file on Windows 10, you need to use %%i.

Nubok
  • 3,113
  • 6
  • 24
  • 45
shubhamr238
  • 714
  • 8
  • 17
32

A one-line bash script would be easy to do - replace *.avi with your filetype:

for i in *.avi; do ffmpeg -i "$i" -qscale 0 "$(basename "$i" .avi)".mov  ; done
yolk
  • 619
  • 7
  • 10
  • The default encoder for .mov is libx264 (if available), but this encoder ignores `-qscale`. Remove it and use the default settings, or use `-crf` instead (default is `-crf 23`). – llogan Aug 14 '16 at 19:29
  • 1
    If there are any spaces in the file name the command will fail because the backticked `basename` subshell isn't quoted. This is exactly why bash has shell expansion instead: for i in *.avi; do ffmpeg -i "$i" -qscale 0 "$(basename "$i" .avi)".mov ; done – Calimo Feb 16 '18 at 12:28
  • thanks @Calimo totally agree - i've updated my answer – yolk May 08 '18 at 22:54
26

To convert with subdirectories use e.g.

find . -exec ffmpeg -i {} {}.mp3 \;
user2707001
  • 1,143
  • 10
  • 13
  • I used this, combined with [this answer](https://superuser.com/a/1093206/) to convert VTT to SRT, to great effect. `find -name "*.vtt" -exec ffmpeg -i {} {}.srt \;` – grooveplex Jun 07 '18 at 19:40
  • I this command, with slight modif to convert all mp4 to mp3: `find *.mp4 -exec ffmpeg -i {} {}.mp3 \;` – swdev Jun 15 '18 at 23:28
  • 1
    Or, if you want to convert multiple file types: `find . -name *.ogg -or -name *.wma -exec ffmpeg -i {} {}.mp3 \;` – bonh Sep 26 '18 at 18:36
  • Convert all wma files to mp3 and after delete them: `find . -name *.wma -exec ffmpeg -i {} {}.mp3 \; -exec rm {} \;` – Panagiotis Dec 21 '19 at 17:35
  • `find **/*.wav -exec ffmpeg -i {} -map 0:a:0 -b:a 96k {}.mp3 \;` – Lance Pollard Dec 17 '20 at 08:38
22

For anyone who wants to batch convert anything with ffmpeg but would like to have a convenient Windows interface, I developed this front-end:

https://sourceforge.net/projects/ffmpeg-batch

It adds to ffmpeg a window fashion interface, progress bars and time remaining info, features I always missed when using ffmpeg.

Eibel
  • 390
  • 3
  • 7
  • 1
    Ok this is a nice project! I have been chasing my tail for an hour trying to get ffmpeg to accept a relative outfile path in Windows and this makes it feel like cheating. EDIT: i used this to convert .xwm to .flac – semtex41 Dec 29 '18 at 22:53
9

@Linux To convert a bunch, my one liner is this, as example (.avi to .mkv) in same directory:

for f in *.avi; do ffmpeg -i "${f}" "${f%%.*}.mkv"; done

please observe the double "%%" in the output statement. It gives you not only the first word or the input filename, but everything before the last dot.

brian d foy
  • 121,466
  • 31
  • 192
  • 551
JayHawk
  • 91
  • 1
  • 1
7

If you have GNU parallel you could convert all .avi files below vid_dir to mp4 in parallel, using all except one of your CPU cores with

find vid_dir -type f -name '*.avi' -not -empty -print0 |
    parallel -0 -j -1 ffmpeg -loglevel fatal -i {} {.}.mp4

To convert from/to different formats, change '*.avi' or .mp4 as needed. GNU parallel is listed in most Linux distributions' repositories in a package which is usually called parallel.

sebbit
  • 91
  • 3
  • 4
  • couldn't you could do the same by adding `!` to the end of any of the bash one-liners? – stib Jan 22 '19 at 07:38
6

Of course, now PowerShell has come along, specifically designed to make something exactly like this extremely easy.

And, yes, PowerShell is also available on other operating systems other than just Windows, but it comes pre-installed on Windows, so this should be useful to everyone.

First, you'll want to list all of the files within the current directory, so, we'll start off with:

ls

You can also use ls -Recurse if you want to recursively convert all files in subdirectories too.

Then, we'll filter those down to only the type of file we want to convert - e.g. "avi".

ls | Where { $_.Extension -eq ".avi" }

After that, we'll pass that information to FFmpeg through a ForEach.

For FFmpeg's input, we will use the FullName - that's the entire path to the file. And for FFmpeg's output we will use the Name - but replacing the .avi at the end with .mp3. So, it will look something like this:

$_.Name.Replace(".avi", ".mp3")

So, let's put all of that together and this is the result:

ls | Where { $_.Extension -eq ".avi" } | ForEach { ffmpeg -i $_.FullName $_.Name.Replace(".avi", ".mp3") }

That will convert all ".avi" files into ".mp3" files through FFmpeg, just replace the three things in quotes to decide what type of conversion you want, and feel free to add any other arguments to FFmpeg within the ForEach.

You could take this a step further and add Remove-Item to the end to automatically delete the old files.

If ffmpeg isn't in your path, and it's actually in the directory you're currently in, write ./ffmpeg there instead of just ffmpeg.

Hope this helps anyone.

ABPerson
  • 408
  • 5
  • 19
  • 1
    PowerShell is great, thanks! In case anyone else runs into trouble running this: put this command in a `.ps1` file, not a `.bat` file. You'll have to run `Set-ExecutionPolicy RemoteSigned` as administrator if you've never run a PS script before. – starpause May 20 '20 at 15:04
  • Well, generally I just thought about running it straight in PowerShell, so I didn't really think of that! Good tip though! – ABPerson May 20 '20 at 17:48
5

I know this might be redundant but I use this script to batch convert files.

old_extension=$1
new_extension=$2

for i in *."$old_extension";
  do ffmpeg -i "$i" "${i%.*}.$new_extension";
done

It takes 2 arguments to make it more flexible :

  1. the extension you want to convert from
  2. the new extension you want to convert to

I create an alias for it but you can also use it manually like this:

sh batch_convert.sh mkv mp4

This would convert all the mkv files into mp4 files.

As you can see it slightly more versatile. As long as ffmpeg can convert it you can specify any two extensions.

Alexander Luna
  • 4,517
  • 4
  • 26
  • 34
3

Getting a bit like code golf here, but since nearly all the answers so far are bash (barring one lonely cmd one), here's a windows cross-platform command that uses powershell (because awesome):

ls *.avi|%{ ffmpeg -i $_ <ffmpeg options here> $_.name.replace($_.extension, ".mp4")}

You can change *.avi to whatever matches your source footage.

stib
  • 2,729
  • 2
  • 23
  • 33
2
for i in *.flac;
  do name=`echo "${i%.*}"`;
  echo $name;
  ffmpeg -i "${i}" -ab 320k -map_metadata 0 -id3v2_version 3 "${name}".mp3;
done

Batch process flac files into mp3 (safe for file names with spaces) using [1] [2]

Community
  • 1
  • 1
César D. Velandia
  • 1,295
  • 10
  • 9
2

windows:

@echo off
for /r %%d in (*.wav) do (
    ffmpeg -i "%%~nd%%~xd" -codec:a libmp3lame -c:v copy -qscale:a 2 "%

%~nd.2.mp3"
)

this is variable bitrate of quality 2, you can set it to 0 if you want but unless you have a really good speaker system it's worthless imo

user151496
  • 1,549
  • 18
  • 30
2

The following script works well for me in a Bash on Windows (so it should work just as well on Linux and Mac). It addresses some problems I have had with some other solutions:

  • Processes files in subfolders
  • Replaces the source extension with the target extension instead of just appending it
  • Works with files with multiple spaces and multiple dots in the name (See this answer for details.)
  • Can be run when the target file exists, prompting before overwriting

ffmpeg-batch-convert.sh:

sourceExtension=$1 # e.g. "mp3"
targetExtension=$2 # e.g. "wav"
IFS=$'\n'; set -f
for sourceFile in $(find . -iname "*.$sourceExtension")
do
    targetFile="${sourceFile%.*}.$targetExtension"
    ffmpeg -i "$sourceFile" "$targetFile"
done
unset IFS; set +f

Example call:

$ sh ffmpeg-batch-convert.sh mp3 wav

As a bonus, if you want the source files deleted, you can modify the script like this:

sourceExtension=$1 # e.g. "mp3"
targetExtension=$2 # e.g. "wav"
deleteSourceFile=$3 # "delete" or omitted
IFS=$'\n'; set -f
for sourceFile in $(find . -iname "*.$sourceExtension")
do
    targetFile="${sourceFile%.*}.$targetExtension"
    ffmpeg -i "$sourceFile" "$targetFile"
    if [ "$deleteSourceFile" == "delete" ]; then
        if [ -f "$targetFile" ]; then
            rm "$sourceFile"
        fi
    fi
done
unset IFS; set +f

Example call:

$ sh ffmpeg-batch-convert.sh mp3 wav delete

Marco Eckstein
  • 3,100
  • 2
  • 29
  • 40
1

Only this one Worked for me, pls notice that you have to create "newfiles" folder manually where the ffmpeg.exe file is located.

Convert . files to .wav audio Code:

for %%a in ("*.*") do ffmpeg.exe -i "%%a" "newfiles\%%~na.wav"
pause

i.e if you want to convert all .mp3 files to .wav change ("*.*") to ("*.mp3").

The author of this script is :

https://forum.videohelp.com/threads/356314-How-to-batch-convert-multiplex-any-files-with-ffmpeg

hope it helped .

Mehrdad995
  • 11
  • 5
1

I'm using this one-liner in linux to convert files (usually H265) into something I can play on Kodi without issues:

for f in *.mkv; do ffmpeg -i "$f" -c:v libx264 -crf 28 -c:a aac -b:a 128k output.mkv; mv -f output.mkv "$f"; done

This converts to a temporary file and then replaces the original so the names remain the same after conversion.

1

I needed all the videos to use the same codec for merging purposes
so this conversion is mp4 to mp4
it's in zsh but should easily be convertible to bash

for S (*.mp4) { ffmpeg -i $S -c:v libx264 -r 30  new$S }
zzapper
  • 4,003
  • 5
  • 44
  • 41
1

I use this for add subtitle for Tvshows or Movies on Windows.

Just create "subbed" folder and bat file in the video and sub directory.Put code in bat file and run.

for /R  %%f in (*.mov,*.mxf,*.mkv,*.webm) do (
    ffmpeg.exe  -i "%%~f" -i "%%~nf.srt" -map 0:v -map 0:a -map 1:s -metadata:s:a language=eng -metadata:s:s:1 language=tur -c copy ./subbed/"%%~nf.mkv"
    )
Teknoist
  • 11
  • 2
  • This works well in a batch file. For anyone trying to use this on the normal command line, use only one percent `%` symbol. – Brad Dec 12 '20 at 00:27
0

If you want a graphical interface to batch process with ffmpegX, try Quick Batcher. It's free and will take your last ffmpegX settings to convert files you drop into it.

Note that you can't drag-drop folders onto Quick Batcher. So select files and then put them through Quick Batcher.

Nirav Mehta
  • 193
  • 1
  • 3
0

Another simple solution that hasn't been suggested yet would be to use xargs:

ls *.avi | xargs -i -n1 ffmpeg -i {} "{}.mp4"

One minor pitfall is the awkward naming of output files (e.g. input.avi.mp4). A possible workaround for this might be:

ls *.avi | xargs -i -n1 bash -c "i={}; ffmpeg -i {} "\${i%.*}.mp4""

telenachos
  • 844
  • 5
  • 18
0

This is what I use to batch convert avi to 1280x mp4

FOR /F "tokens=*" %%G IN ('dir /b *.avi') DO "D:\Downloads\ffmpeg.exe" -hide_banner -i "%%G" -threads 8 -acodec mp3 -b:a 128k -ac 2 -strict -2 -c:v libx264 -crf 23 -filter:v "scale=1280:-2,unsharp=5:5:1.0:5:5:0.0" -sws_flags lanczos -b:v 1024k -profile:v main -preset medium -tune film -async 1 -vsync 1 "%%~nG.mp4"

Works well as a cmd file, run it, the loop finds all avi files in that folder.

calls MY (change for yours) ffmpeg, passes input name, the settings are for rescaling up with sharpening. I probs don't need CRF and "-b:v 1024k"...

Output file is input file minus the extension, with mp4 as new ext.

brian d foy
  • 121,466
  • 31
  • 192
  • 551
Morphy
  • 1
0

This will create mp4 video from all the jpg files from current directory.

echo exec("ffmpeg -framerate 1/5 -i photo%d.jpg -r 25 -pix_fmt yuv420p output.mp4");
0

And for Windows, this does not work

FOR /F "tokens=*" %G IN ('dir /b *.flac') DO ffmpeg -i "%G" -acodec mp3 "%~nG.mp3"

even if I do double those %.

I would even suggest:

-acodec ***libmp3lame***

also:

FOR /F "tokens=*" %G IN ('dir /b *.flac') DO ffmpeg -i "%G" -acodec libmp3lame "%~nG.mp3"
brian d foy
  • 121,466
  • 31
  • 192
  • 551
  • 3
    Is this an answer, or an attempt to post a new question as an answer? In the latter case, please create a completely new question instead, though possibly linking back here for background. – tripleee Jun 12 '20 at 05:59
0

Also if you want same convertion in subfolders. here is the recursive code.

for /R "folder_path" %%f in (*.mov,*.mxf,*.mkv,*.webm) do (
    ffmpeg.exe -i "%%~f" "%%~f.mp4"
    )
0

For giggles, here's solution in fish-shell:

for i in *.avi; ffmpeg -i "$i" (string split -r -m1 . $i)[1]".mp4"; end
steevee
  • 1,678
  • 17
  • 15
-2

little php script to do it:

#!/usr/bin/env php
<?php
declare(strict_types = 1);
if ($argc !== 2) {
    fprintf ( STDERR, "usage: %s dir\n", $argv [0] );
    die ( 1 );
}
$dir = rtrim ( $argv [1], DIRECTORY_SEPARATOR );
if (! is_readable ( $dir )) {
    fprintf ( STDERR, "supplied path is not readable! (try running as an administrator?)" );
    die(1);
}
if (! is_dir ( $dir )) {
    fprintf ( STDERR, "supplied path is not a directory!" );
    die(1);
}
$files = glob ( $dir . DIRECTORY_SEPARATOR . '*.avi' );
foreach ( $files as $file ) {
    system ( "ffmpeg -i " . escapeshellarg ( $file ) . ' ' . escapeshellarg ( $file . '.mp4' ) );
}
hanshenrik
  • 15,263
  • 3
  • 28
  • 61
  • 3
    A very limited scope answer as a user has to have PHP installed on their machine. The command line and batch file answers are much easier, and much less complex. – ProfK Nov 10 '17 at 09:06
  • 2
    @ProfK [PHP is 1 of the most popular languages on SO](https://insights.stackoverflow.com/survey/2017) - second, Isaac's answer for sh is somewhat unreliable, in that it might rename your files to something else than the original, for example, it doesn't preserve newlines in the filename. lyx's bat script is even worse, it __COMPLETELY IGNORES__ any file with newlines in the name. not sure why, not even a syntax error or anything, but it does (tested on win10). my php script has neither problems, thanks to `escapeshellarg()`, and works both on windows and linux. i agree its a edge-case though. – hanshenrik Nov 12 '17 at 12:43