6

Convert directory of videos to MP4 in parallel

for path in *.avi; do echo "${path%.avi}"; done | xargs -I{} -P9 HandBrakeCLI -i {}.avi -o {}.mp4

August 13, 2013shavenwarthog

Explanation

This one-liner uses the wonderful HandBrakeCLI tool to convert videos to MP4 format, in parallel.

The one-liner solves 2 challenges:

  • Format input filenames from something.avi into something.mp4.
  • Execute the video converter tool for many files in parallel.

To convert filenames we use Parameter Substitution: given path=something.avi, the value of ${path%.avi} is something, with the .avi extension dropped.

To convert all filenames this way we use the loop:

for path in *.avi; do echo "${path%.avi}"; done

With xargs -I{} -P9 ... we can execute up to 9 commands in parallel. In the command we can use {} to inject the value of the input line. In this example the input lines are base filenames without extensions, so when the input line is somefile, to convert somefile.avi to somefile.mp4, we can use {}.avi and {}.mp4, respectively.

And so with HandBrakeCLI -i {}.avi -o {}.mp4 we execute the video converter with the correct input filename and intended output filename.

Another version of this writeup is on my blog: https://johntellsall.blogspot.com/2013/08/converting-video-for-media-player.html

Limitations

Requires the Handbrake tool, install from https://handbrake.fr/ The tool also has a pretty GUI if you don't like the terminal :)