Created
January 3, 2011 19:11
-
-
Save BinaryMuse/763786 to your computer and use it in GitHub Desktop.
Rename files inside the ~/Desktop/Screenshots folder to something slightly more sane.
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 | |
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment