Skip to content

Instantly share code, notes, and snippets.

@floehopper
Created December 27, 2021 11:26
Show Gist options
  • Save floehopper/374170dd3a92d71aaeca4ea187b2279c to your computer and use it in GitHub Desktop.
Save floehopper/374170dd3a92d71aaeca4ea187b2279c to your computer and use it in GitHub Desktop.
Flatten files in sub-directories into single directory
#!/usr/bin/env ruby
require 'pathname'
require 'fileutils'
pwd = Pathname.pwd
begin
source = Pathname.new(ARGV[0].nil? ? pwd : ARGV[0]).realpath
destination = Pathname.new(ARGV[1].nil? ? pwd: ARGV[1]).realpath
rescue Errno::ENOENT
abort 'Usage: flatten [source-path] [destination-path]'
end
source.glob('**/*').each do |source_path|
next unless source_path.file?
relative_path = source_path.relative_path_from(pwd)
flattened_path = relative_path.each_filename.drop_while { |s| s.to_s == '.' }.map(&:to_s).join(' - ')
target_path = destination.join(flattened_path)
next if target_path.exist?
puts "#{relative_path} -> #{flattened_path}"
FileUtils.cp source_path, target_path
end
@floehopper
Copy link
Author

I think I used this to process files exported from iCloud photos.

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