Created
June 25, 2016 00:59
-
-
Save preetpalS/30313a6faf52df93d5895bcd058867ba to your computer and use it in GitHub Desktop.
Script to left pad numeric filenames with leading 0's
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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