Skip to content

Instantly share code, notes, and snippets.

@mhayes
Last active August 29, 2015 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mhayes/066ea78643ebcd4d2ef0 to your computer and use it in GitHub Desktop.
Save mhayes/066ea78643ebcd4d2ef0 to your computer and use it in GitHub Desktop.
Need quick way to rename files according to a sequence?

quickstart

Let's assume you have OS X screenshots named like Screen Shot 2015-06-09 at 9.39.56 AM.png. You can use this script to rename them like so:

mark:screens mark$ ruby renamer.rb 
move ./Screen Shot 2015-06-09 at 9.39.56 AM.png to EXAMPLE_ONE_160x600_1.png
move ./Screen Shot 2015-06-09 at 9.39.57 AM.png to EXAMPLE_ONE_160x600_2.png
move ./Screen Shot 2015-06-09 at 9.39.58 AM.png to EXAMPLE_ONE_160x600_3.png
move ./Screen Shot 2015-06-09 at 9.40.00 AM.png to EXAMPLE_ONE_160x600_4.png
move ./Screen Shot 2015-06-09 at 9.40.30 AM.png to EXAMPLE_TWO_160x600_1.png
move ./Screen Shot 2015-06-09 at 9.40.31 AM.png to EXAMPLE_TWO_160x600_2.png
move ./Screen Shot 2015-06-09 at 9.40.32 AM.png to EXAMPLE_TWO_160x600_3.png
move ./Screen Shot 2015-06-09 at 9.40.34 AM.png to EXAMPLE_TWO_160x600_4.png
require "fileutils"
names = %w{EXAMPLE_ONE EXAMPLE_TWO}
sizes = %w{160x600-4}
expanded_sizes = sizes.map do |s|
new_sizes = []
size = s.split("-")
dims = size[0]
variations = size[1].to_i
variations.times do |i|
new_sizes << "#{dims}_#{i+1}"
end
new_sizes
end
expanded_sizes.flatten!
sizes = []
names.each do |name|
sizes << expanded_sizes.map {|size| "#{name}_#{size}"}
end
sizes.flatten!
files = Dir.glob("./Screen*").sort_by {|pth| File.mtime(pth)}
raise Exception unless sizes.length == files.length
files.each_with_index do |path, idx|
puts "move #{path} to #{sizes[idx]}.png"
FileUtils.mv path, "#{sizes[idx]}.png"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment