Skip to content

Instantly share code, notes, and snippets.

@Beyarz
Last active August 9, 2024 17:57
Show Gist options
  • Save Beyarz/05396f3c945b9557922e584ed507b84b to your computer and use it in GitHub Desktop.
Save Beyarz/05396f3c945b9557922e584ed507b84b to your computer and use it in GitHub Desktop.
Flatten a directory structure and its hierarchy. This script moves every file in a subfolder to its parent and then delete the subfolder
# frozen_string_literal: true
# Put me in a folder where you want to get rid of all the subfolders
# Run: ruby flatten.rb
def move_and_delete(dir)
puts "Cleaning \"#{dir}\""
Dir.foreach(dir) do |file|
next if ['.', '..'].include?(file)
source = File.join(dir, file)
parent_path = File.dirname(dir)
target = File.join(parent_path, file)
if Dir.exist?(source)
puts "\"#{source}\" is a folder, emptying it"
move_and_delete(source)
elsif File.file?(source)
File.rename(source, target)
puts "Moved \"#{file}\" to \"#{File.dirname(dir)}\""
end
end
return move_and_delete(dir) unless Dir.empty?(dir)
Dir.rmdir(dir)
puts "Deleted directory: \"#{dir}\""
end
current_dir = ARGV.empty? ? Dir.pwd : File.expand_path(ARGV[0])
puts "Flattening all subdirectories in folder \"#{current_dir}\""
print 'Press any key to continue'
STDIN.gets.chomp
Dir.foreach(current_dir) do |entry|
next if ['.', '..'].include?(entry)
full_path = File.join(current_dir, entry)
move_and_delete(full_path) if File.directory?(full_path)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment