AppleScriptTips
目次
動作サンプルなど
デスクトップにファイル類を作成
- 新規フォルダを作成する
tell application "Finder" make folder at desktop with properties {name:"untitled"} -- make new Finder window to (path to desktop folder) -- 単純にFinderウィンドウを表示させるのではなく、以下のようにした方がいいかも -- set newFolder to make folder at desktop with properties {name:"untitled"} -- reveal newFolder end tell
- http://docs.info.apple.com/jarticle.html?path=AppleScript/2.1/jp/as176.html make
- http://docs.info.apple.com/jarticle.html?path=AppleScript/2.1/jp/as177.html set
- http://docs.info.apple.com/jarticle.html?path=AppleScript/2.1/jp/as1010.html reveal
- http://docs.info.apple.com/jarticle.html?path=AppleScript/2.1/jp/as186.html フォルダ
- http://docs.info.apple.com/jarticle.html?path=AppleScript/2.1/jp/as130.html
- http://docs.info.apple.com/jarticle.html?path=AppleScript/2.1/jp/as189.html path to
do shell script "/bin/mkdir ~/Desktop/untitled/"
set theName to "untitled" set thePath to POSIX path of (((path to desktop folder) as string) & theName & ":") do shell script "/bin/mkdir " & quoted form of thePath
- 同名のフォルダがあった場合、末尾に番号を付加した名前で作成
tell application "Finder" set theName to "untitled" set num to "" repeat until not (exists folder (theName & num) of desktop) -- repeat while (exists folder (theName & num) of desktop) -- 付加する番号は1から set num to (num as number) + 1 -- 付加する番号は2から -- if num = "" then set num to 1 -- set num to num + 1 end repeat set theName to theName & num make folder at desktop with properties {name:theName} -- make new Finder window to (path to desktop folder) end tell
- 多重の新規フォルダを作成する
set theStr to "Book:Mac:AppleScript:Neuburg, Matt:" set orgDelim to AppleScript's text item delimiters set AppleScript's text item delimiters to ":" set dirNames to every text item of theStr set AppleScript's text item delimiters to orgDelim tell application "Finder" set curFolder to desktop repeat with theName in dirNames if theName as string is "" then exit repeat set newFolder to make folder at curFolder with properties {name:theName} set curFolder to newFolder end repeat -- make new Finder window to (path to desktop folder) end tell
- 新規ファイルを作成する
tell application "Finder" make file at desktop with properties {name:"untitled.txt"} -- make file with properties {name:"untitled.txt", file type:"TEXT", container:desktop} -- make new Finder window to (path to desktop folder) end tell
tell application "System Events" make new file at end of files of (path to desktop) with properties {name:"untitled.txt"} end tell -- tell application "Finder" to make new Finder window to (path to desktop folder)
- インターネット・ロケーションファイルを作成する
set theTitle to "MacWiki" set theURL to "http://macwiki.sourceforge.jp/wiki/" tell application "Finder" make internet location file at desktop to theURL with properties {name:theTitle} -- make new Finder window to (path to desktop folder) end tell
- 同名のファイルがあった場合、拡張子の前に番号を付加した名前で作成
tell application "Finder" set theName to "untitled.draft.txt" set {theName, theExtension} to getStemExt(theName) of me set num to "" repeat until not (exists file (theName & num & theExtension) of desktop) -- repeat while (exists file (theName & num & theExtension) of desktop) -- 付加する番号は1から set num to (num as number) + 1 -- 付加する番号は2から -- if num = "" then set num to 1 -- set num to num + 1 end repeat set theName to theName & num & theExtension make file at desktop with properties {name:theName} -- make new Finder window to (path to desktop folder) end tell on getStemExt(theStr) -- m/^([^.]*)(\.?.*)$/ set origDelim to AppleScript's text item delimiters set AppleScript's text item delimiters to "." set splitStr to every text item of theStr set AppleScript's text item delimiters to origDelim set num to number of splitStr set theStem to item 1 of splitStr set theExtension to "" if num > 1 then repeat with idx from 2 to num set theExtension to theExtension & "." & item idx of splitStr end repeat end if return {theStem, theExtension} end getStemExt
theExtension は通常の拡張子、つまり「untitled.draft.txt」で言えば「.txt」ではなく、「.draft.txt」となるが、これを普通に「.txt」(Finder (Mac OS X) で name extension of theFile などとして得られるもの ← これだと正確には.なしの「txt」) にするには例えば下のようにする。
on getStemExt(theStr) set origDelim to AppleScript's text item delimiters set AppleScript's text item delimiters to "." set splitStr to every text item of theStr set AppleScript's text item delimiters to origDelim set num to number of splitStr set theStem to item 1 of splitStr set theExtension to "" if num > 1 then repeat with idx from 2 to (num - 1) set theStem to theStem & "." & item idx of splitStr end repeat set theExtension to theExtension & "." & item num of splitStr end if return {theStem, theExtension} end getStemExt
- 多重の新規フォルダおよびファイルを作成する
set theStr to "Book:Mac:AppleScript:Neuburg, Matt:untitled.txt" set orgDelim to AppleScript's text item delimiters set AppleScript's text item delimiters to ":" set dirNames to every text item of theStr set AppleScript's text item delimiters to orgDelim tell application "Finder" set revNames to reverse of dirNames set fName to first item of revNames if fName is not "" then set dirNames to reverse of rest of revNames set curFolder to desktop repeat with theName in dirNames if theName as string is "" then exit repeat set newFolder to make folder at curFolder with properties {name:theName} set curFolder to newFolder end repeat if fName is not "" then make file at curFolder with properties {name:fName} -- make new Finder window to (path to desktop folder) end tell
- ファイル類のあるディレクトリのパスと名前を取得する
パスがスラッシュ区切りの場合、":"の代わりに"/"とすればいい。
set aPath to "Macintosh HD:Users:someone:Documents:untitled.draft.txt" set {theContainer, theName} to getPathNames(aPath) of me on getPathNames(thePath) set theDelim to ":" as Unicode text if thePath ends with theDelim then -- フォルダの場合、最後のtheDelimを省く set thePath to text 1 thru -2 of thePath end if set curPath to text 1 thru -(offset of theDelim in (reverse of characters of thePath) as string) of thePath set curName to text ((length of thePath) - (offset of theDelim in (reverse of characters of thePath) as string) + 2) thru -1 of thePath return {curPath, curName} end getPathNames
ファイルのクリエータを変更する (旧Mac OS向き)
下にあるようにアプリケーションソフトを表す MMKE といったクリエータコードを使って set creator type of theFile to "MMKE" でクリエータを変更できます。ファイルタイプ を変更することは少ないでしょうが同様に set file type of theFile to "TEXT" のようにして変更できます。
- ドロップレットにドラッグ&ドロップされたファイルのクリエータを変更
on open theItemsDropped tell application "Finder" repeat with anItem in theItemsDropped if (class of item anItem is document file) and (name of anItem ends with ".txt") then -- 書類ファイル以外を処理しないようにする安全対策 -- if file type of anItem is "TEXT" then -- ファイルタイプでテキストであるか判定 -- if name of anItem ends with ".txt" then -- ファイル名の末尾でテキストであるか判定 -- if name extension of anItem is "txt" then -- 拡張子でテキストであるか判定 (旧Mac OS向きではない) -- if (creator type of anItem is "MSWD") and (name of anItem does not end with ".doc") then -- 複数の条件 set creator type of anItem to "MMKE" -- mi のクリエータコード end if end repeat end tell end open
- Finderで選択しているファイルのクリエータを変更
tell application "Finder" try set FinderSelection to selection as alias list on error set FinderSelection to selection end try repeat with anItem in FinderSelection if (class of item anItem is document file) and (name of anItem ends with ".txt") then -- if file type of anItem is "TEXT" then -- if name of anItem ends with ".txt" then -- ファイル名の終了文字列を指定 -- if name extension of anItem is "txt" then -- if (name extension of anItem is "txt") or (name extension of anItem is "tex") then -- 複数の条件 -- if name of anItem starts with "log" then -- ファイル名の開始文字列を指定 -- if "draft" is in name of anItem then -- ファイル名に含まれる文字列を指定 -- if name of anItem contains "draft" then set creator type of anItem to "MMKE" end if end repeat end tell
ファイルの他の属性を変更する (set creator type of aFile to "MMKE" の替わりの例)
- ラベルを変更する
set label index of aFile to 2 -- 0にすればラベルなしになる
- ロックする
set locked of aFile to true -- falseにすればロック解除
- コメントを変更する
set comment of aFile to (current date) as string -- 現在の日時をコメント欄に書き込む
set comment of aFile to (modification date of aFile) as string -- 修正日時をコメント欄に書き込む
- 拡張子を非表示にする (Mac OS X)
set extension hidden of aFile to true
ファイル類の(カラー)ラベルを変更
ファイル・メニューからラベルは容易に変更できるが、純粋に選択されているファイル類のラベルだけが変更され、フォルダ内の項目までは処理されない。every file of entire contents of theFolderといったものでフォルダ内の全階層のファイルなど扱えることを利用して、選択されているフォルダ内の全階層のファイル類も処理する。
- Finderで選択しているファイル類の(カラー)ラベルを変更
tell application "Finder" try set FinderSelection to selection as alias list on error set FinderSelection to selection end try repeat with anItemSelected in FinderSelection -- 選択されたものだけを処理 set label index of anItemSelected to 2 -- 0にすればラベルなしになる -- フォルダが選択されている場合、そのフォルダ内の全階層のファイル類を処理 if (anItemSelected as string) ends with ":" then -- フォルダの場合 -- if folder (anItemSelected as string) exists then -- or as Unicode Text -- if class of anItemSelected is folder then -- if kind of anItemSelected is "フォルダ" then -- Mac OS X (日本語環境) 向き set aList to every item of entire contents of anItemSelected repeat with anItem in aList set label index of anItem to 2 end repeat end if end repeat end tell
ファイル類のアクセス権 (パーミッション) を変更
- Finderで選択しているファイル類のアクセス権を変更
tell application "Finder" try set FinderSelection to selection as alias list on error set FinderSelection to selection end try repeat with anItem in FinderSelection set {owner privileges of anItem, group privileges of anItem, everyones privileges of anItem} ¬ to {read write, read only, read only} end repeat end tell
- http://docs.info.apple.com/jarticle.html?path=AppleScript/2.1/jp/as177.html set
- http://docs.info.apple.com/jarticle.html?path=AppleScript/2.1/jp/as179.html item
- http://adg.bne.jp/takenote/note/AppleScript/index.html#20040406130876211
- http://cwoweb2.bai.ne.jp/thumb3/AS/
- http://docs.info.apple.com/jarticle.html?artnum=107039
- http://okwave.jp/qa2527987.html
ファイル類のパス文字列を得る
ファイルのHFSパス文字列を得るためには,"~ as alias" だけでは日本語ファイル名が中途で切り捨てられてしまうようです.(システムは MacOSX 10.4.7 です.バグなのかもしれませんが)下記のように,"(~ as alias) as string" とすれば良いようです.
tell application "Finder" to set filelist to selection as list set aFile to item 1 of filelist set aFile_str_hfs to (aFile as alias) as string -- set the clipboard to aFile_str_hfs -- これの実行結果例は,"HD:Users:username:myapps:LogoVista辞典ブラウザ" といったもの
ファイルのPOSIXパス文字列を得るには,
set aFile_str_posix to (POSIX path of (aFile as Unicode text)) as Unicode text
- http://docs.info.apple.com/jarticle.html?path=AppleScript/2.1/jp/as208.html POSIX path
- http://www.tonbi.jp/AppleScript/dic/OSAX/Value/POSIX_file.html
- http://www.seuzo.jp/rubbs/search_html/msg01375.html
- GetPath http://hp.vector.co.jp/authors/VA031742/GetPath.html
- http://tech.mit.oops.jp/?eid=48145
- http://blogs.dion.ne.jp/fujidana/archives/752249.html
- http://blogs.dion.ne.jp/fujidana/archives/756894.html
- http://blogs.dion.ne.jp/fujidana/archives/756944.html
- http://kotoerisan.blog16.fc2.com/blog-entry-209.html
- http://www.h5.dion.ne.jp/~tuyano/Tankoubon/X-AS.html
- http://nolobe.com/scripting/2007/03/08/copy-path/
最も手前のフォルダー(Finderのウィンドウ)のパスを取得する(シェルスクリプトとして仕立てた例):
#!/bin/sh /usr/bin/osascript -e 'tell application \"Finder\" to get POSIX path of (target of window 1 as string)
#!/bin/sh echo " tell application \"Finder\" get POSIX path of (target of window 1 as string) end tell " |osascript -
ファイル類の名前を変更 (リネーム)
- Finderで選択しているファイル類の名前の頭に文字列を追加
tell application "Finder" set addStr to text returned of (display dialog "ファイル名の頭に付加する文字列を入力" default answer "") if addStr is "" then return -- 終了 try set FinderSelection to selection as alias list on error set FinderSelection to selection end try repeat with aFile in FinderSelection set oldName to name of aFile set newName to addStr & oldName -- set newName to oldName & addStr -- 文字列を後に追加 set theFolder to container of aFile as string if not (exists item newName of folder theFolder) then set name of aFile to newName else display dialog "「" & oldName & "」は名称変更しませんでした。" end if end repeat end tell
- Finderで選択しているファイル類の名前の開始文字列を削除
tell application "Finder" set cutLen to text returned of (display dialog "ファイル名の先頭から何文字消去しますか?" default answer "0") if cutLen as number = 0 then return -- 終了 try set FinderSelection to selection as alias list on error set FinderSelection to selection end try repeat with aFile in FinderSelection set oldName to name of aFile set len to number of oldName set newName to (characters (cutLen + 1) thru len of oldName) as string -- set newName to (characters 1 thru (len - cutLen) of oldName) as string -- 終了文字列を消去 set theFolder to container of aFile as string if not (exists item newName of folder theFolder) then set name of aFile to newName else display dialog "「" & oldName & "」は名称変更しませんでした。" end if end repeat end tell
- Shupapan http://sunsky3s.s41.xrea.com/
- ReNa X http://www.vector.co.jp/soft/mac/util/se286630.html
- PowerRenamer http://homepage.mac.com/tkurita/scriptfactory/Softwares/FinderHelpers/PowerRenamer/index.html
- NameChanger http://web.mac.com/mickeyroberson/iWeb/MRR%20Software/NameChanger.html
- File Buddy http://www.skytag.com/filebuddy/jp/9/downloads.html
- ドロップレットにドラッグ&ドロップされたファイル類の名前を連番にする
- フォーマット文字列の%のところを0を頭に詰めた4桁の数字にした名前に変更する (新居さんのスクリプトを改変)
- http://www.msyk.net/macos/script/filerenamer.html
on open theItemsDropped set nameFormat to text returned of (display dialog "ファイル名のパターンを指定:%が数字に置き換わる" default answer "MyPhoto%.jpg") set pos to offset of "%" in nameFormat set len to length of nameFormat set nameHead to (characters 1 thru (pos - 1) of nameFormat) set nameTail to (characters (pos + 1) thru len of nameFormat) tell application "Finder" set num to 1 set newName to nameHead & "0001" & nameTail as string repeat with aFile in theItemsDropped -- repeat with aFile in sort theItemsDropped by name -- 現在の名前でソート後に処理 -- repeat with aFile in sort theItemsDropped by modification date -- 変更日 (修正日) でソート (新旧の順) 後に処理 -- repeat with aFile in reverse of (sort theItemsDropped by modification date) -- 変更日 (修正日) でソート (旧新の順) 後に処理 set theFolder to container of aFile as string repeat until not (exists file newName of folder theFolder) set num to num + 1 set numText to "000" & num as string set numLen to length of numText set numText to (characters (numLen - 3) thru numLen of numText) as string set newName to nameHead & numText & nameTail as string end repeat set name of aFile to newName as string end repeat end tell end open
テキストをプレーンテキスト (プレインテキスト) にする
- クリップボード内のテキストをプレインテキスト (プレインテクスト) にする
set the clipboard to «class ktxt» of ((the clipboard as text) as record)
- http://www.macosxhints.com/article.php?story=20040204170653788
- http://docs.info.apple.com/jarticle.html?path=AppleScript/2.1/jp/as195.html set the clipboard to
- http://docs.info.apple.com/jarticle.html?path=AppleScript/2.1/jp/as196.html the clipboard
- http://www.tonbi.jp/AppleScript/tips/String/StyledText.html
- http://www1.odn.ne.jp/~cge02410/backnumber/2006/12/19174503.html
- Strip Styles of Text
- getPlainText
- PlaintextPaste という contextual menu でも同じ機能を実現できます
- Plain Clip というアプリケーションもあります。
- 他の方法として、Cocoa アプリケーションの内部で pasteAsPlainText を動作させる方法もあります。
エイリアスファイルを,それと同等のシンボリックリンクへ変更する.
display dialog "エイリアスファイルを捨てて,シンボリックリンクを作成します." if button returned of result is "OK" then tell application "Finder" repeat with anItem in selection -- 選択されたファイル if kind of anItem is "エイリアス" then try set aPath to POSIX path of (original item of anItem as alias) set linkPath to (POSIX path of (anItem as text)) delete anItem -- ゴミ箱へ捨てる do shell script "/bin/ln -s '" & aPath & "' '" & linkPath & "'" end try end if end repeat end tell end if
- mSymbolicLink
- エイリアスファイルとシンボリックリンクを区別判定できる AppleScript があればさらに嬉しいですね.
- MacOSXエイリアス読み (http://cwoweb2.bai.ne.jp/thumb3/AS/) というスクリプトを見ると、ファイルタイプをみて「slnk」ならシンボリックリンクであるという判定をしているようですが、詳しいことはわかりません。
文字列操作
- 文字列の1文字をランダムに選択する
set theStr to "アップルScript" set aChar to some character of theStr -- set aChar to character (random number from 1 to number of theStr) of theStr
- 逆さの文字列を得る
set theStr to "まさかさ" set revStr to "" repeat with aChar in every character of theStr set revStr to aChar & revStr end repeat -- display dialog revStr
set theStr to "まさかさ" -- set revStr to reverse of (every text item of theStr) as string set revStr to reverse of (characters of theStr) as string -- display dialog revStr
- 半角英字の大文字を小文字へ
set theText to "AppleScript アップルスクリプト AppleScript" set newText to "" repeat with aChar in every character of theText set asNum to ASCII number aChar if (asNum > 64) and (asNum < 91) then set aChar to ASCII character (asNum + 32) -- tr/A-Z/a-z/ -- if (asNum > 96) and (asNum < 123) then set aChar to ASCII character (asNum - 32) -- tr/a-z/A-Z/ set newText to newText & aChar end repeat -- display dialog newText
set chars to {¬ {uc:"A", lc:"a", ucj:"A", lcj:"a"}, {uc:"B", lc:"b", ucj:"B", lcj:"b"}, ¬ {uc:"C", lc:"c", ucj:"C", lcj:"c"}, {uc:"D", lc:"d", ucj:"D", lcj:"d"}, ¬ {uc:"E", lc:"e", ucj:"E", lcj:"e"}, {uc:"F", lc:"f", ucj:"F", lcj:"f"}, ¬ {uc:"G", lc:"g", ucj:"G", lcj:"g"}, {uc:"H", lc:"h", ucj:"H", lcj:"h"}, ¬ {uc:"I", lc:"i", ucj:"I", lcj:"i"}, {uc:"J", lc:"j", ucj:"J", lcj:"j"}, ¬ {uc:"K", lc:"k", ucj:"K", lcj:"k"}, {uc:"L", lc:"l", ucj:"L", lcj:"l"}, ¬ {uc:"M", lc:"m", ucj:"M", lcj:"m"}, {uc:"N", lc:"n", ucj:"N", lcj:"n"}, ¬ {uc:"O", lc:"o", ucj:"O", lcj:"o"}, {uc:"P", lc:"p", ucj:"P", lcj:"p"}, ¬ {uc:"Q", lc:"q", ucj:"Q", lcj:"q"}, {uc:"R", lc:"r", ucj:"R", lcj:"r"}, ¬ {uc:"S", lc:"s", ucj:"S", lcj:"s"}, {uc:"T", lc:"t", ucj:"T", lcj:"t"}, ¬ {uc:"U", lc:"u", ucj:"U", lcj:"u"}, {uc:"V", lc:"v", ucj:"V", lcj:"v"}, ¬ {uc:"W", lc:"w", ucj:"W", lcj:"w"}, {uc:"X", lc:"x", ucj:"X", lcj:"x"}, ¬ {uc:"Y", lc:"y", ucj:"Y", lcj:"y"}, {uc:"Z", lc:"z", ucj:"Z", lcj:"z"}} set theText to "AppleScript アップルスクリプト AppleScript" set newText to "" repeat with aChar in every character of theText repeat with c in chars if aChar as string is uc of c then set aChar to lc of c -- tr/A-Z/a-z/ -- if aChar as string is lc of c then set aChar to uc of c -- tr/a-z/A-Z/ end repeat set newText to newText & aChar end repeat -- display dialog newText
リスト操作
- リストの要素をランダムに選択する
set theList to {"coffee", "tea", "milk", "water", "soup"} set anItem to some item of theList -- set anItem to item (random number from 1 to number of theList) of theList -- set anItem to item (random number from 1 to length of theList) of theList
- ランダムな1からnまでの正整数のリストを得る
nが大きいと不味そうだけど、
set numList to {} set n to 5 repeat until (number of numList is n) set getNum to random number from 1 to n if numList does not contain getNum then set end of numList to getNum end repeat
- リストの要素をランダムに並び替える
set theList to {"coffee", "tea", "milk", "water", "soup"} set newList to {} set numList to {} set n to number of theList repeat until (number of numList is n) set getNum to random number from 1 to n if numList does not contain getNum then set end of numList to getNum end repeat repeat with idx in numList set end of newList to item idx of theList end repeat
set theList to {"coffee", "tea", "milk", "water", "soup"} set n to number of theList set tmpList to {"dummy"} & theList & {"dummy"} set newList to {} repeat with idx from n to 1 by -1 set getNum to random number from 1 to idx set end of newList to item (getNum + 1) of tmpList set tmpList to (items 1 thru getNum of tmpList) & (items (getNum + 2) thru -1 of tmpList) end repeat
set theList to {"coffee", "tea", "milk", "water", "soup"} set n to number of theList set newList to {} repeat with idx from n to 1 by -1 set getNum to random number from 1 to idx set end of newList to item getNum of theList if getNum = 1 then set theList to rest of theList else if getNum = idx then set theList to rest of reverse of theList else set theList to (items 1 thru (getNum - 1) of theList) & (items (getNum + 1) thru -1 of theList) end if end repeat
set theList to {"coffee", "tea", "milk", "water", "soup"} set n to number of theList repeat with idx from n to 1 by -1 set getNum to random number from 1 to idx if idx is not getNum then set {item idx of theList, item getNum of theList} to {item getNum of theList, item idx of theList} end if end repeat
- 重複する要素を取り除く
set theList to {"water", "coffee", "tea", "soup", "milk", "water", "soup"} set newList to {} repeat with anItem in theList if newList does not contain anItem then set newList to newList & anItem end if end repeat
日付
- 和暦を得る
set twelveSigns to {"子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"} set thisYear to year of (current date) set thisSign to item ((thisYear - 1900) mod 12 + 1) of twelveSigns -- 十二支 if thisYear < 1912 then set thisWareki to "明治" & (thisYear - 1867) & "年" else if thisYear < 1926 then set thisWareki to "大正" & (thisYear - 1911) & "年" else if thisYear < 1989 then set thisWareki to "昭和" & (thisYear - 1925) & "年" else set thisWareki to "平成" & (thisYear - 1988) & "年" end if display dialog "西暦" & thisYear & "年は " & thisWareki & "," & thisSign & "年 です。"
- http://www.drycarbon.com/applescript/tips/karino/date.html
- DateStamp http://hp.vector.co.jp/authors/VA031742/datestamp.html
- http://blog.goo.ne.jp/vallie/e/57613efac590132f612453716c94f2dd
- 年号野郎 http://www.asahi-net.or.jp/~mn5h-nks/nengou/
- 換暦 http://maechan.net/kanreki/
- CalendarCalcT (JavaScript) http://hp.vector.co.jp/authors/VA030824/ja/Application/CalendarCalcT-J.html
- http://www.fct.co.jp/benri/nenrei/sei-wa-conv.html