前に日付に関するAppleScript を書いたので、その延長で今度は、ファイルの
「変更日」をファイル名の末尾に付加するスクリプトを書いてみました。
Finder で「日付」を付けたいファイルを選択して、スクリプトを実行します。
そうすると、ファイル名の末尾に「-20180321」という具合に変更日が付加されます。
「オリジナルのファイル名_年月日の数字8桁.拡張子」というフォーマットです。
※ Finder の環境設定で、ファイルの拡張子を表示しない場合では、ちゃんとスクリプトが動くかどうか試していないので、あしからず。
該当のファイルを編集し「変更日」が変わったとしても、自動でファイル名が変更されるわけではないのでご注意を。その都度、ファイルを選択してスクリプトを実行して下さい。
(フォルダアクションに対応させるとかで、自動化できそうな気もするけど、ファイルの自動保存とかかち合いそう?)
それと、フォルダやアプリケーションファイルなどには適用されません。
AppleScript でファイルの参照を as string で文字列にしたときに、フォルダの場合は文字列の最後が「:」になる、これを利用してファイルかフォルダかを判別しています。
実のところはフォルダだけど、ファイルのように振る舞う「ファイル」(例えばアプリケーション .app など)も「フォルダ」と判定し、変更日の日付を付加しません。
例外として、画像ファイル付きのリッチテキストファイル .rtfd と
スケッチファイル .sketch に関しては、スクリプトが適用されるようにしています。
各自でこのような「ファイル」を追加したいときは、冒頭のリスト excludedExtsList に、該当する拡張子を付け加えることで実現できます。
(わざわざ、property で宣言しなくてもいいと思うけど、久しぶりだから使ってみた)
以下、ソース。
property excludedExtsList : {"rtfd", "sketch"}
on run
tell application "Finder" to set slectedItems to selection as alias list
if slectedItems is {} then
else
mainRoutine(slectedItems)
end if
end run
on mainRoutine(theItems)
tell application "Finder"
repeat with eachItem in theItems
set existDateString to false
set theExt to name extension of eachItem
if (eachItem as string) does not end with ":" or excludedExtsList contains theExt then
set theDate to (modification date of eachItem)
set theYY to year of theDate as text
set theMM to my zeroPrefix(month of theDate as integer)
set theDD to my zeroPrefix(day of theDate as integer)
set dateString to theYY & theMM & theDD
set fileName to (displayed name of eachItem) as string
set theExtLength to (length of theExt)
set theName to (characters 1 thru -(theExtLength + 2) of fileName) as string
set theNameLength to length of theName
if theNameLength > 9 then
set underBar to character (theNameLength - 8) of theName
set prevDateString to ((characters (theNameLength - 7) thru -1) of theName) as string
if underBar is "_" and (length of prevDateString is 8) then
try
get prevDateString as integer
set aMonth to my removeZero(characters 5 thru 6 of prevDateString)
set aDay to my removeZero(characters 7 thru 8 of prevDateString)
if (1 ≤ aMonth and aMonth ≤ 12) and (1 ≤ aDay and aDay ≤ 31) then
if prevDateString is dateString then
set existDateString to true
else
set existDateString to false
set theName to((
characters 1 thru (theNameLength - 9)) of theName) as string
end if
end if
end try
end if
end if
if existDateString is false then
try
set name of eachItem to theName & "_" & dateString & "." & theExt
end try
end if
end if
end repeat
end tell
end mainRoutine
on zeroPrefix(num)
if num < 10 then
return ("0" & (num as text))
else
return (num as text)
end if
end zeroPrefix
on removeZero(aList)
if (item 1 of aList) is "0" then
return (item 2 of aList) as integer
else
return (aList as string) as integer
end if
end removeZero
「すでにファイル名に変更日が付加されているかどうか」を判定する箇所が、if の連続でもう少しスマートにできないものかと (´・ω・`)