Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save preetpalS/30313a6faf52df93d5895bcd058867ba to your computer and use it in GitHub Desktop.
Save preetpalS/30313a6faf52df93d5895bcd058867ba to your computer and use it in GitHub Desktop.
Script to left pad numeric filenames with leading 0's
require 'pathname'
DIRECTORIES_TO_IGNORE = ['.git']
EXTENSIONS_TO_IGNORE = [ # not implemented
/^.git*$/,
'.DS_Store'
].freeze
MINIMUM_WIDTH = 3
MOVE_COMMAND = ->(current_path, destination_path) {
# Change `git mv` to `mv`/`move` on (Linux/OS-X/*BSD)/Windows for use outside of a git repository
system "git mv #{current_path} #{destination_path}"
}
PATH = '.'
RECURSE_DIRECTORY_PREDICATE = false
def leftpad_numeric_filenames_with_zeros(path, recursive = false)
path.children.each do |child_path|
if child_path.directory?
leftpad_numeric_filenames_with_zeros(child_path, recursive) if
recursive &&
!(DIRECTORIES_TO_IGNORE.map { |dir| child_path.relative_path_from(PATH) != dir }.reduce { |a, b| a && b })
else
begin
filename_without_extension = child_path.basename.to_s.sub(/\..*/, '')
if Integer(filename_without_extension)
original_path = child_path.cleanpath
destination_path = "#{child_path.dirname}/#{filename_without_extension.rjust(MINIMUM_WIDTH, '0')}#{child_path.extname}"
puts "Moving #{original_path} to #{destination_path}."
MOVE_COMMAND.call(original_path, destination_path)
end
rescue => e
# puts e
# puts "#{child_path} not touched."
end
end
end
end
path = Pathname.new(PATH)
leftpad_numeric_filenames_with_zeros(path, RECURSE_DIRECTORY_PREDICATE)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment