ファイルをタイムスタンプ付きでコピーするAppleScriptを作った

How to copy files with timestamp in AppleScript.


Macでファイルをコピーしてバックアップするときに毎回右クリックして複製を選ぶのが面倒だったので、
(あと"コピー 2"みたいなファイル名のファイルができるのが嫌だったので)
AppleScriptを作った。

まずAppleScript エディタを起動する。
(アプリケーション > ユーティリティ の中にある)


下記の囲みの中をAppleScriptにコピーする。

on open dorp_Items
	tell application "Finder"
		-- システム日付を取得する / get system date time
		set {year:yyyy, month:mo, day:dd, hours:hh, minutes:mi, seconds:ss} to (current date)
		-- 月を数値形式に変換する / convert month(String) to month(Integer)
		set moInt to (mo as integer)
		-- 前ゼロを付与する(2桁にする)/ set zero in front of number(make 2 digit)
		set moInt to my setZero(moInt)
		set dd to my setZero(dd)
		set hh to my setZero(hh)
		set mi to my setZero(mi)
		set ss to my setZero(ss)
		-- タイムスタンプを作成する "YYYYMODDHHMISS"/ make timestamp
		set timestamp to (yyyy & moInt & dd & hh & mi & ss)
		
		repeat with obj in dorp_Items
			-- 元のファイル名を取得する / get original file name
			set filenameOrigine to name of obj as string
			-- ファイルの拡張子を取得する / get file extension 
			set ext to name extension of obj
			
			-- タイムスタンプ付きのファイル名を作成する / make filename with timestamp
			if ext is not "" then
				-- 拡張子なしのファイル名を取得する / get filename without extension
				set filenameLength to (count of filenameOrigine) - (count of ext) - 1
				set filenameNoExt to text 1 thru filenameLength of filenameOrigine
				-- タイムスタンプを連結する / conbine filename with timestamp
				set filenameCopy to (filenameNoExt & timestamp & "." & ext)
			else
				-- タイムスタンプを連結する / conbine filename with timestamp
				set filenameCopy to (filenameOrigine & timestamp)
			end if
			
			-- 元のファイルをコピーする / copy original file
			set newfile to duplicate obj
			-- ファイル名をタイムスタンプ付きのもの変更する / change filename to filename with timestamp
			set name of newfile to filenameCopy
		end repeat
	end tell
end open

-- 前ゼロを付与する(2桁にする)/ set zero in front of number(make 2 digit)
on setZero(param)
	if param < 10 then
		set paramWithZero to ("0" & param)
	else
		set paramWithZero to param
	end if
	return paramWithZero
end setZero


ファイルフォーマットを「アプリケーション」で保存する。


できたアイコンにファイルを&ドロップすると、そのファイルをコピーする
コピー後のファイル名は「元のファイル名+タイムスタンプ」。


参考にしたサイト:
AppleScript Language Guide (公式)
https://developer.apple.com/library/mac/documentation/applescript/conceptual/applescriptlangguide/introduction/ASLR_intro.html
AppleScript 最速基本文法マスター
http://mc909j.blogspot.jp/2013/03/applescript.html
Re: duplicate file and rename
https://discussions.apple.com/message/13357783
APPLESCRIPT: GET NAME OF FILES IN A FOLDER WITHOUT EXTENSION
http://www.geekality.net/2010/11/26/applescript-get-name-of-files-in-a-folder-without-extension/
Dates & Times in AppleScripts
http://macscripter.net/viewtopic.php?id=24737


英語でもコメントしているのはAppleScriptがマイナー言語らしく(はてなスーパーpre記法もAppleScript無かった・・)、
情報が少ないので、日本語のサイトでも外国人が見るかもと思ったから。
世界に羽ばたくプログラマーってやつ?
⬅羽でも何でも生やして飛んでけよ。俺は飛行機で行くわwwとつっこみたい。