Batch Transcode Videos with Find, Xargs, and FFmpeg
Efficiently processing large numbers of video files is a common task
for developers and multimedia administrators. This guide demonstrates
how to combine the Unix find command, xargs,
and ffmpeg to automate and parallelize the batch
transcoding of video files. By chaining these commands, you can scan
directories recursively, handle filenames with spaces safely, and
utilize multiple CPU cores to speed up your rendering pipeline.
The Standard Batch Transcoding Command
To recursively find all .mkv files in a directory and
transcode them to .mp4 using the H.264 video codec and AAC
audio codec, run the following command in your terminal:
find . -type f -name "*.mkv" -print0 | xargs -0 -I {} -P 2 sh -c 'ffmpeg -y -nostdin -i "$0" -c:v libx264 -crf 23 -c:a aac "${0%.*}.mp4"' {}Command Breakdown
To customize this pipeline for your specific workflow, it is important to understand how each component operates:
1. The find Command
.: Instructs the command to start searching from the current working directory.-type f: Restricts the search results exclusively to files.-name "*.mkv": Filters the search to match only files ending with the.mkvextension.-print0: Prints the full file path followed by a null character (instead of a newline). This is crucial because it ensures filenames containing spaces, quotes, or unusual characters are interpreted correctly by the next command.
2. The xargs Command
-0: Tellsxargsto expect null-character-terminated input, perfectly matching the output offind -print0.-I {}: Defines{}as a placeholder for the input argument (the file path).-P 2: Specifies the number of parallel processes to run. In this case,xargswill process up to two videos simultaneously. You can increase this number based on your system’s CPU capabilities.sh -c '...' {}: Launches a system shell to safely execute inline shell manipulations, passing the file path placeholder{}as argument$0.
3. The ffmpeg Command
-y: Automatically overwrites any existing output files without asking for confirmation.-nostdin: This flag is critical. By default, FFmpeg allows interactive user input from the standard input (stdin) to pause or cancel processing. Becausexargsalso uses stdin to pass file lists, FFmpeg will conflict withxargsand prematurely terminate the batch job unless-nostdinis declared.-i "$0": Specifies the input file path passed from the shell argument.-c:v libx264 -crf 23: Encodes the video using the H.264 codec at a Constant Rate Factor (CRF) of 23 (a balanced setting for quality and file size).-c:a aac: Encodes the audio track to AAC format."${0%.*}.mp4": Strips the original file extension (e.g.,.mkv) and appends.mp4to name the new transcoded file.