先に書き出したファイルを削除+_HHmmssを削除

先に書き出したファイルを削除+_HHmmssを削除するAppleScriptです。
20200407-001_085012.tif
20200407-001_102341.tif
以上のようなフォーマットのファイルがあった時、日付の古い方を削除し、
最新のファイルを「20200407-001」部分を残しリネームするものです。
※ファイル名を基準にしています。ファイルのExif等を基準にしたものではないのでご注意を。
20200407-001_085012.tif(こちらを削除)
20200407-001_102341.tif → 20200407-001.tif に。

-- https://detail.chiebukuro.yahoo.co.jp/qa/question_detail/q13222731298#a537908671
-- http://piyocast.com/as/archives/3653
-- http://piyocast.com/as/archives/695

use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

property NSCountedSet : a reference to current application's NSCountedSet
set sourceFolder to path to desktop folder -- ソースフォルダ
set fileType to "TIFFイメージ" -- "PNGイメージ" -- ファイルの種類

tell application "Finder"
set aList to (every file of sourceFolder whose kind of it is fileType) as alias list
-- ソースフォルダにある全てのファイルを検索し、指定した種類のファイルでフィルタリング
if aList is {} then return
set ext to name extension of (item 1 of aList) -- 拡張子を取得
end tell


set bList to {}
repeat with i in aList
set bList to bList & (TID(fileNameExtraction(contents of i) of me, "_", 1) of me)
-- ファイル名を抽出し、“_”で分割。一つ目のアイテムを取り出し。
end repeat

set aRes to returnDuplicatesOnly(bList) of me -- 重複のみを抽出

set cList to {}
tell application "Finder"
repeat with j in aRes
set k to contents of j
set the end of cList to {sort ((every file of sourceFolder whose name starts with k and kind of it is fileType)) by name}
end repeat

repeat with m in cList
set bRes to item 1 of (contents of m)
delete (items 1 thru -2 of bRes)
set changedName to TID(TID(name of (last item of bRes), "_", 1) of me, ".", 1) of me & "." & ext
set name of (last item of bRes) to changedName
end repeat
end tell


on fileNameExtraction(anAlias)
tell application "Finder"
set fName to name of anAlias
end tell
return fName
end fileNameExtraction

on TID(orgText, splChar, itemNo)
set tmpDelimiters to AppleScript's text item delimiters
set AppleScript's text item delimiters to splChar
set str to text item itemNo of orgText
set AppleScript's text item delimiters to tmpDelimiters
return str
end TID

on returnDuplicatesOnly(aList as list)
set aSet to NSCountedSet's alloc()'s initWithArray:aList
set bList to (aSet's allObjects()) as list

set dupList to {}
repeat with i in bList
set aRes to (aSet's countForObject:i)
if aRes > 1 then
set the end of dupList to (contents of i)
end if
end repeat

return dupList
end returnDuplicatesOnly

更新履歴

inserted by FC2 system