音楽製作しているとファイルの管理、特にファイル名の管理は何かと多いですよね?Macにもファインダーの「ファイル/名前を変更」、または直接複数のファイルを選択したのちに右クリックで「名称変更…」を選んでファイル名の編集できますね。
確かに単語の置き換え、例えばファイル名の中の小文字のstemをやっぱり大文字のSTEMに変更したいな、、、と思った時などは右クリックからファイル名の変更ができて便利なのですが、文字を削除する編集はこの「名前を変更」ではできないんですね。というわけでこれもスクリプト書いていつでも使えるようにしちゃいましょう。前回と同じく以下をまるっとスクリプトエディタ.appで新規ファイルを作成してコピペしちゃってください。
-- ファイルを選択するダイアログを表示
set theFiles to choose file with prompt "対象とするファイルを選択してください:" with multiple selections allowed
-- 元のファイル名とフルパスを保存するリスト
set originalPaths to {}
set newPaths to {}
-- 先頭を削除するか、末尾を削除するかを選択
set cutSide to button returned of (display dialog "先頭から削除しますか、それとも末尾から削除しますか?" buttons {"先頭", "末尾"} default button "先頭")
-- 削除する文字数を入力
set numChars to text returned of (display dialog "削除する文字数を入力してください:" default answer "0")
set numChars to numChars as integer
-- 実行するか再確認
set confirmChoice to button returned of (display dialog "ファイル名から" & numChars & "文字を" & cutSide & "から削除します。よろしいですか?" buttons {"はい", "いいえ"} default button "いいえ")
if confirmChoice is "はい" then
repeat with aFile in theFiles
set filePath to POSIX path of aFile
set fileName to name of (info for aFile)
set nameExt to name extension of (info for aFile)
if nameExt is not "" then
set baseName to text 1 thru ((length of fileName) - (length of nameExt) - 1) of fileName
else
set baseName to fileName
end if
set newName to ""
if cutSide is "先頭" then
if length of baseName > numChars then
set newName to text (numChars + 1) thru (length of baseName) of baseName
end if
else
if length of baseName > numChars then
set newName to text 1 thru ((length of baseName) - numChars) of baseName
end if
end if
if newName is not "" then
if nameExt is not "" then
set newFileName to newName & "." & nameExt
else
set newFileName to newName
end if
-- 新しいフルパスを作成
set newPath to (POSIX path of (POSIX file (do shell script "dirname " & quoted form of filePath))) & "/" & newFileName
-- ファイルのパスを保存
copy filePath to end of originalPaths
copy newPath to end of newPaths
-- シェルコマンドでファイル名を変更
do shell script "mv " & quoted form of filePath & " " & quoted form of newPath
end if
end repeat
end if
-- Undo操作を提案
set undoChoice to button returned of (display dialog "Undoしますか?" buttons {"はい", "いいえ"} default button "いいえ")
if undoChoice is "はい" then
repeat with i from 1 to count of originalPaths
set originalPath to item i of originalPaths
set newPath to item i of newPaths
-- シェルコマンドで元に戻す
do shell script "mv " & quoted form of newPath & " " & quoted form of originalPath
end repeat
end if
今回も細かい説明はしませんが、ワンポイントだけ、先頭の”choose file”を”choose folder”に変更すればファイル単位ではなくフォルダ単位でファイル名の変更ができる仕様になります。
僕がこれを使うのは、例えばProToolsからサウンドデザインしている途中に選択したリージョンを外部にエクスポートしたファイルを後からまとめて整理する時なんです。下のスナップショット画像のように、ファイル名の末尾に「-01」という数字がどうしても付いちゃうんですが、ここから先モジュラーシンセに持って行ってサウンドデザインを続けたり、Ableton Liveでしかできない処理のためにファイルを移動させたりする際にこの末尾の数字がない方が気分的にスッキリします(個人の感想ですが)。というわけでこういうスクリプトを書いて、「ファイル名の先頭から○文字削除、またはファイル名の末尾から○文字削除」できるようにしておくと時間の節約になります。
次回はこのスクリプトを右クリックから実行できるようにする手順を説明します。