Skip to content

Instantly share code, notes, and snippets.

@wilkerlucio
Created January 23, 2009 14:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wilkerlucio/51029 to your computer and use it in GitHub Desktop.
Save wilkerlucio/51029 to your computer and use it in GitHub Desktop.
Batch rename mp3 files
#!/usr/bin/env ruby
require "rubygems"
require "id3lib"
File.instance_eval do
def mp3?(path)
File.extname(path).downcase == '.mp3'
end
end
class Mp3Renamer
class << self
def rename_file(file)
begin
name = format_name(file)
puts "Renaming #{File.basename(file)} to #{name}..."
File.rename(file, File.dirname(file) + "/" + name)
rescue
puts
puts "Error renaming #{File.basename(file)}"
puts
end
end
def rename_directory(dir)
dir_scan(dir) do |file|
next unless File.mp3? file
rename_file file
end
end
private
def dir_scan(directory, &block)
Dir.foreach(directory) do |file|
next if [".", ".."].include? file
path = directory + "/" + file
if File.directory? path
dir_scan path, &block
else
yield path if block_given?
end
end
end
def format_name(file)
tag = ID3Lib::Tag.new(file, ID3Lib::V1)
"#{tag.track.rjust(2, '0')} - #{tag.artist} - #{tag.title}.mp3"
end
end
end
base_path = $*[0] || "."
if $*.include? '--install'
require 'win32/registry.rb'
puts "Installing shell extension..."
shell = Win32::Registry::HKEY_CLASSES_ROOT.open("Directory\\shell")
unless shell.keys.include? 'id3_renamer'
shell.create('id3_renamer') do |reg|
reg.write('', Win32::Registry::REG_SZ, "Rename files by ID3")
reg.create("command") do |command|
command.write("", Win32::Registry::REG_SZ, "\"C:\\ruby\\bin\\ruby.exe\" \"#{File.expand_path __FILE__}\" \"%1\"")
end
end
end
else
Mp3Renamer.rename_directory(base_path)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment