Skip to content

Instantly share code, notes, and snippets.

@X0nic
Last active January 2, 2016 06:09
Show Gist options
  • Save X0nic/8261458 to your computer and use it in GitHub Desktop.
Save X0nic/8261458 to your computer and use it in GitHub Desktop.
Rename mp3s based on tags
#!/usr/bin/env ruby
# Thanks to: Ahmad Azizan
# http://blog.lab69.com/2012/02/renaming-mp3-files-with-ruby.html
# You need to require this..
require 'rubygems'
require 'mp3info'
# This variable will hold your first argument as directory
# that contains mp3 files
dir = ARGV[0]
dir = File.expand_path(dir)
# Scan for files with .mp3 extension
mp3_list = Dir.glob("#{dir}/*.mp3")
# Initialize variable 'artist' and 'song'
artist = ''
song = ''
# Loop all the list of files inside the array
mp3_list.each do |mp3_file|
Mp3Info.open(mp3_file) do |mp3|
if mp3.tag.artist.nil?
# If artist tag not found, set as 'Unknown'
artist = "Unknown"
else
# If found, assign to variable artist.
# replace character '/' to '\' to avoid
# problem in renaming the file.
artist = mp3.tag.artist.gsub(/\//,"\\")
end
if mp3.tag.title.nil?
# If title tag not found, set as 'Unknown'
song = "Unknown"
else
# If found, assign to variable song.
# replace character '/' to '\' to avoid
# problem in renaming the file.
song = mp3.tag.title.gsub(/\//,"\\")
end
# combine as a new path
new_name = "#{dir}/#{artist} - #{song}#{File.extname(mp3_file)}"
unless mp3_file == new_name
# If looping filename != newly combined path,
# rename the file
puts new_name
File.rename(mp3_file, new_name)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment