Skip to content

Instantly share code, notes, and snippets.

@djk29a
Last active September 30, 2016 18:38
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 djk29a/a5310c011d8d3532614c372f02d3bb82 to your computer and use it in GitHub Desktop.
Save djk29a/a5310c011d8d3532614c372f02d3bb82 to your computer and use it in GitHub Desktop.
Remove duplicate files in iTunes as a result of Consolidate Files
require 'find'
root = '/Volumes/music' # pick your path
Find.find(root) do |path|
if FileTest.directory? path and File.basename(path)[0] == '.'
Find.prune
else
d, f = File.split path
if f =~ /^(\d+(\-\d+)?.+)(\s\d+)\.(mp3)$/i
orig_file = File.join(d, $1 + '.' + $4) # check for existence of original file name including extension case
if File.readable? orig_file
puts "O: #{$1 + '.mp3'}, deleting #{f}..."
begin
File.unlink(path)
rescue
puts "Error deleting #{f} in #{d}, try later outside here"
end
end
end
end
end
require 'find'
require 'fileutils'
root = '/Volumes/music' # pick your path
Find.find(root) do |path|
if FileTest.directory? path
if File.basename(path)[0] == '.'
Find.prune
else
next
end
else
# look for folder.jpg / cover.jpg
if path =~ /(.jpg)$/i
dir, filename = File.split path
basedir, albumdir = File.split dir
if albumdir =~ /^(?:\d+\s\-\s)(.+)/
itunes_dname = File.join(basedir, $1)
puts "Checking for directory #{itunes_dname}: "
if File.directory? itunes_dname and File.readable? itunes_dname
puts "\e[32mOK\e[0m"
tgt = File.join(itunes_dname, filename)
if path == tgt
puts "Already in ok path. Skipping"
else
puts "Moving: #{path} to #{tgt}"
FileUtils.mv(path, File.join(itunes_dname, filename))
end
else
puts "\e[31mNOK\e[0m"
end
end
end
end
end
@djk29a
Copy link
Author

djk29a commented Apr 6, 2016

Danger I hit during run of this script is using it on an AFP volume with different UTF-8 variants (why the rescue condition was hit surprisingly frequently, especially with my Germanic, Scandinavian origin songs - seems there was a mix of ISO-8559-1 with UTF-8 for just umlauts? Ugh). You'll want to make sure that your UTF-8 encodings reconcile with the OS as well as how OS X defaults (Google for rsync iconv utf-8-mac to get started on the rabbit hole). I wound up modifying the FreeNAS afpd configuration to use the OS X encoding always since there's no clients other than Macs that will use AFP and FreeBSD and Linux are both more flexible than OS X on this matter.

@djk29a
Copy link
Author

djk29a commented Apr 6, 2016

And if it's not obvious, this will totally break any file references that iTunes or other programs would have to the deleted files.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment