public
Created

Rename files inside the ~/Desktop/Screenshots folder to something slightly more sane.

  • Download Gist
rename-sshots.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
#!/usr/bin/env ruby
 
# Rename files inside the ~/Desktop/Screenshots folder to something
# slightly more sane. Called via a folder action, but does not
# use any parameters from the action (the script scans for the files.)
#
# Example original filenames:
# ScreenCapture 2011-01-03 at 8.06.39 AM.png
# ScreenCapture 2011-01-03 at 8.06.39 AM (2).png
# Example destination filenames:
# screencap_2011-01-03_08-06-39.png
# screencap_2011-01-03_08-06-39_2.png
#
# Note this script only works with my customizations to the defaults
# com.apple.screencapture name (ScreenCapture) and
# com.apple.screencapture location (~/Desktop/Screenshots).
# Adjust as necessary.
 
require 'pp'
 
SCREENSHOT_FOLDER = '/Users/BinaryMuse/Desktop/Screenshots'
# http://rubular.com/r/0mtUw9fq6s
SCREENCAP_REGEX = /ScreenCapture (\d*)-(\d*)-(\d*) at (\d*)\.(\d*)\.(\d*) ([A-Z]{2})( \(([^\.\)]*)\))?\.(.*)/i
 
# Convert an hour and a meridian to a 24-hour time.
def mil_hour(hour, meridian)
hour = hour.to_i
# Special cases at noon and midnight. All other times += 12 during PM.
if hour == 12
hour = 0 if meridian == "AM"
else
hour += 12 if meridian == "PM"
end
"%02d" % hour
end
 
Dir["#{SCREENSHOT_FOLDER}/*"].each do |file|
basename = File.basename(file)
matches = basename.scan(SCREENCAP_REGEX).flatten
next if matches.empty?
 
# Convert matches to hash for easier reference
parts = {}
[:year, :month, :day, :hour, :minute, :second, :meridian, :_, :suffix, :extension].each_with_index do |sym, i|
parts[sym] = matches[i]
end
 
# date part
new_name = "screencap_#{parts[:year]}-#{parts[:month]}-#{parts[:day]}_"
# time part
new_name += "#{mil_hour(parts[:hour], parts[:meridian])}-#{parts[:minute]}-#{parts[:second]}"
# suffix, if any
new_name += "_#{parts[:suffix]}" unless parts[:suffix].nil?
# extension
new_name += ".#{parts[:extension]}"
 
File.rename(file, "#{SCREENSHOT_FOLDER}/#{new_name}")
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.