Created
July 18, 2009 12:57
-
-
Save pcdavid/149546 to your computer and use it in GitHub Desktop.
numerote.rb
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
#!/usr/bin/env ruby | |
######################################## | |
# numerote.rb | |
# Author: Pierre-Charles David ([email protected]) | |
# Version: 0.1 | |
# Depends on: nothing (except Ruby) | |
# License: General Public License (GPL, see http://www.gnu.org/gpl) | |
# A very simple Ruby script useful to rename a set of files | |
# consistently. When invoked like this "numerote.rb prefix [start]" it | |
# will rename all the files contained in the current directory in the | |
# form "prefix-nb.ext" where: | |
# | |
# - 'prefix' is a fixed string, given as the first argument of the script. | |
# - 'nb' is a number incremented for each file. Files are processed in | |
# sorted order according to their original names. The numbering starts | |
# from 0, unless a starting index is given as the second argument | |
# (start). Numbers are padded to the left with zeros so that all resulting | |
# file names will have the same width (ex: file-00.xml ... file-67.xml). | |
# - 'ext' is the original extension of the file, and is left untouched. | |
# | |
# Sample run: | |
# % ls | |
# foo.jpg bar.png baz.mov | |
# % numerote.rb | |
# Usage: numerote prefix [start] | |
# % numerote.rb qux 99 | |
# % ls | |
# qux-099.png qux-100.mov qux-101.jpg | |
# | |
# As I said, the script is very simple (read dumb), and doesn't handle | |
# renaming conflicts. It is your responsibility to make sure | |
# everything will work correctly. | |
if ARGV.length != 1 && ARGV.length != 2 then | |
puts "Usage: numerote prefix [start]" | |
exit | |
end | |
prefix = ARGV.shift | |
index = ARGV.shift.to_i or 0 | |
fileNames = Dir["*"].select { |name| FileTest.file?(name) } | |
width = Math.log10(index + fileNames.length).ceil | |
format = prefix + "-%0" + width.to_s + "d" | |
renamings = Hash.new | |
fileNames.sort.each do |name| | |
ext = (name.scan(/\.[^\.]+$/)[0] or '') | |
renamings[name] = (format % index) + ext | |
index += 1 | |
end | |
renamings.each_pair do |oldName, newName| | |
# puts "#{oldName} => #{newName}" | |
File.rename(oldName, newName) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment