Created
September 27, 2012 04:16
-
-
Save kylefox/3792117 to your computer and use it in GitHub Desktop.
Sequentially renames files in a directory.
This file contains hidden or 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
#!/usr/bin/env ruby -wKU | |
# encoding: UTF-8 | |
# | |
# Sequentially renames *all* files in a directory. | |
# You'll be prompted for a filename prefix (ex: "image-") and will | |
# be shown a preview of the new filenames before the rename is performed. | |
# | |
# Installation: | |
# 1) Symlink this script somewhere on your $PATH, ex: `ln -s fileseq.rb /usr/local/bin/fileseq` | |
# 2) Make it executable: `chmod +x /usr/local/bin/fileseq` | |
# | |
# Usage: | |
# 1) Change to the directory containing the files you want to rename: `cd ~/photos` | |
# 2) Follow the prompts and enter a prefix for each file: 'vacation-2012-' | |
# 3) You'll be shown a preview of all the renames (DSC_1234.jpg => vacation-2012-1.jpg, DSC_1235.jpg => vacation-2012-2.jpg, etc) | |
# 4) Choose 'Y' to perform the rename or 'n' to abort. | |
# | |
# IMPORTANT: the files are renamed according to the sequence they appear in initially. | |
# | |
puts("You're about to sequentially rename the files in this directory with a common prefix.") | |
print("Enter the prefix for the new filenames: ") | |
prefix = gets().chomp | |
def get_filenames(prefix) | |
files = Dir.glob("*.*") | |
result = {} | |
files.sort_by.each_with_index do |old_filename, index| | |
result[old_filename] = "#{prefix}#{index+1}#{File.extname(old_filename).downcase}" | |
end | |
result | |
end | |
filenames = get_filenames(prefix) | |
longest_name = filenames.keys.sort_by(&:length).last.length + 4 | |
puts "\nHere's what the result will look like:\n\n" | |
filenames.each do |old_name, new_name| | |
puts "#{old_name.rjust(longest_name)} : #{new_name}" | |
end | |
print "\nDoes this look correct? [Y/n] " | |
looks_right = gets().chomp | |
puts | |
if looks_right == "Y" | |
filenames.each do |old_name, new_name| | |
puts "#{old_name.rjust(longest_name)} => #{new_name}" | |
File.rename(old_name, new_name) | |
end | |
puts "\nFinished renaming #{filenames.length} files." | |
else | |
puts "Rename aborted. Whew!" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment