Skip to content

Instantly share code, notes, and snippets.

@SleepingInsomniac
Created March 28, 2020 14:52
Show Gist options
  • Select an option

  • Save SleepingInsomniac/89930e7ab702ab3c070433188f7014f7 to your computer and use it in GitHub Desktop.

Select an option

Save SleepingInsomniac/89930e7ab702ab3c070433188f7014f7 to your computer and use it in GitHub Desktop.
Move music duplicates to a different location for deletion
#!/usr/bin/env ruby
require 'digest/sha1'
require 'json'
require 'fileutils'
Dir.chdir("/Users/alex/Library/Mobile\ Documents/com\~apple\~CloudDocs/Music/")
search_dir = "library"
trash_dir = "/tmp/duplicates/"
def search(directory, depth = 0)
puts "#{directory}"
dups = {}
Dir.entries(directory).each do |entry|
next if entry.start_with?('.')
path = File.join(directory, entry)
if File.directory?(path)
dups = dups.merge(search(path, depth + 1))
else
print(" " * depth * 2)
puts entry
digest = Digest::SHA1.hexdigest(File.read(path))
dups[digest] ||= []
dups[digest] << path
end
end
dups
end
puts "\n\n"
duplicates = search(search_dir)
.values
.reject do |files|
files.length < 2
end
duplicates.each do |dups|
dups = dups.sort do |a, b|
a.length <=> b.length
end
dups.shift
dups.each do |dup|
puts "Moving #{dup}"
mov_loc = File.dirname(File.join(trash_dir, dup))
FileUtils.mkdir_p(mov_loc)
FileUtils.mv(dup, mov_loc)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment