FFMpeg and Converting Entire Folders of Files – Added Bonus Renaming All the Files you Converted
Using FFMPEG to convert a whole folder of videos is actually a lot easier than you would think. Lets take a look at a really basic bash script to do so.
#!/bin/bash DIR=/Users/tom/Desktop/Video for i in `find $DIR -type f`; do ffmpeg -i $i $i.mpg done
Thats it, just make sure to change the DIR variable to where you are working at, this could be made to take user input easily also or to just work in the current directory but that is up to you as to how you use it and change it. Here is a small change you can make that will make this script infinitely more useful.
#!/bin/bash DIR=/Users/tom/Desktop/Video for i in `find $DIR -type f`; do ffmpeg -i $i $i.mpg ffmpeg -itsoffset -4 -i $i -vcodec mjpeg -vframes 1 -an -f rawvideo -s 200x200 $i.jpg done
Adding the next ffmpeg line makes you a nice thumbnail for your video that is 200×200, again you can modify to your needs easily.
Well now we have our files converted but since we didn’t work any magic in the bash script to convert them we have some ugly file names. For instance you may have before had the file video.avi and you converted it to an mpg so now we have video.avi.mpg. That won’t do so lets look at a really simple ruby script to parse the directory and rename our files how we want.
#!/usr/bin/env ruby def get_input system('clear') puts "What directory will I be working in? ( \e[32mMust be absolute path\e[0m )" directory = gets directory.chomp! end def parse_directory(directory) basedir = directory file_stack = Array.new Dir.new(basedir).entries.each do |file| unless File.directory?(file) file_stack.push file end end return file_stack end def bulk_rename(file_stack) file_stack.each do |file| command = "mv #{file} " file.gsub!('.avi.mpg','.mpg') command << file system command print '.' end print "\n" end file_stack = parse_directory(get_input) puts "I found \e[34m#{file_stack.nitems}\e[0m files" bulk_rename(file_stack) puts "Looks like I am done please type \e[31mls -l\e[0m to make sure I didn't mess up!\n"
This script is actually much shorter than it looks but it handles some basic user input so you can run this and let it know what directory to work in. I use this same script alot to rename a directory of files to other extentions or what ever. The line that has file.gsub!('.avi.mpg','.mpg') can be changes to any 'Pattern', 'Replacement' that you need. This script is not perfect by any means so use that at your own risk.