Basic

[基本]through


サンプルコード

サンプルソース(参考)
行番号ソース
001
002###一文字づつ取り出す
003set strText to "あいう" as text
004
005set strItemString to (text 1 through 1 of strText) as text
006log strItemString
007-->(*あ*)
008
009set strItemString to (text 2 through 2 of strText) as text
010log strItemString
011-->(*い*)
012
013set strItemString to (text 3 through 3 of strText) as text
014log strItemString
015-->(*う*)
016
017#2文字目から最後まで
018set strText to "あいうえお" as text
019set strItemString to (text 2 through -1 of strText) as text
020log strItemString
021
022#2文字目から2文字
023set strText to "あいうえお" as text
024set strItemString to (text 2 through 3 of strText) as text
025log strItemString
026
027
028
029###文字毎に取り出す
030set strText to "あいうえお" as text
031
032set numCntText to (count of strText) as integer
033
034repeat with itemCharNo from 1 to numCntText by 1
035  
036  set strItemString to (text itemCharNo through itemCharNo of strText) as text
037  log strItemString
038  -->
039  (*あ*)
040  (*い*)
041  (*う*)
042  (*え*)
043  (*お*)
044end repeat
045
046###桁数を決めて取り出す
047set strText to "987651234" as text
048
049set numCntText to (count of strText) as integer
050
051#後方4桁を取り出す
052set strItemString to (text (numCntText - 4 + 1) through -1 of strText) as text
053log strItemString
054-->(*1234*)
055
056#前方5桁を取り出す
057set strItemString to (text 1 through 5 of strText) as text
058log strItemString
059-->(* 98765*)
060
061
AppleScriptで生成しました

|

ファイルの上書きチェックとファイル名変更


【スクリプトエディタで開く】|

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.8"
use framework "Foundation"
use framework "AppKit"
use scripting additions

property refMe : a reference to current application


set strFilePath to ("~/Library/LaunchAgents/com.dropbox.DropboxMacUpdate.agent.plist")
set ocidFilePathStr to refMe's NSString's stringWithString:(strFilePath)
set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
set ocidFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidFilePath) isDirectory:false)


set ocidFilePath to doChkExists(ocidFilePathURL)
log ocidFilePath as text


####################################
#上書きチェック
# ocid file path = NSPathStore を返します
####################################
to doChkExists(argFilePath)
log (className() of argFilePath) as text
  if (class of argFilePath) is text then
log "テキストファイルパス"
    set ocidFilePathStr to refMe's NSString's stringWithString:(argFilePath)
    set ocidArgFilePath to ocidFilePathStr's stringByStandardizingPath()
  else if (class of argFilePath) is alias then
log "エリアスファイルパス"
    set strArgFilePath to (POSIX path of argFilePath) as text
    set ocidFilePathStr to refMe's NSString's stringWithString:(argFilePath)
    set ocidArgFilePath to ocidFilePathStr's stringByStandardizingPath()
  else if (class of argFilePath) is «class furl» then
log "エリアスfurlファイルパス"
    set aliasFilePath to argFilePath as alias
    set strArgFilePath to (POSIX path of argFilePath) as text
    set ocidFilePathStr to refMe's NSString's stringWithString:(argFilePath)
    set ocidArgFilePath to ocidFilePathStr's stringByStandardizingPath()
  else if (className() of argFilePath as text) contains "NSCFString" then
log "NSStringファイルパス"
    set ocidArgFilePath to argFilePath's stringByStandardizingPath()
  else if (className() of argFilePath as text) contains "NSPathStore" then
log "NSPathStore2ファイルパス"
    set ocidArgFilePath to argFilePath
  else if (className() of argFilePath as text) contains "NSURL" then
log "NSURLファイルパス"
    set ocidArgFilePath to argFilePath's |path|
  end if
  ####
  set appFileManager to refMe's NSFileManager's defaultManager()
  set boolExists to appFileManager's fileExistsAtPath:(ocidArgFilePath) isDirectory:(false)
  #
  if boolExists = true then
    ##ダイアログを前面に
    set strName to (name of current application) as text
    if strName is "osascript" then
      tell application "Finder" to activate
    else
      tell current application to activate
    end if
    set strMes to "上書きします?" as text
    try
      set objResponse to (display alert strMes buttons {"上書きする", "処理を中止する", "ファイル名を変更"} default button "上書きする" cancel button "処理を中止する" as informational giving up after 20)
    on error
log "処理を中止しました"
return "処理を中止しました"
      error number -128
    end try
    if true is equal to (gave up of objResponse) then
log "時間切れですやりなおしてください"
return "時間切れですやりなおしてください"
      error number -128
    end if
    if "上書きする" is equal to (button returned of objResponse) then
log "上書き保存します"
      set ocidReturnFilePath to ocidArgFilePath
    else if "ファイル名を変更" is equal to (button returned of objResponse) then
log "ファイル名を変更"
      set ocidContainerDirFilePath to ocidArgFilePath's stringByDeletingLastPathComponent()
      set strFileName to ocidArgFilePath's lastPathComponent() as text
      set aliasContainerDirPath to (POSIX file (ocidContainerDirFilePath as text)) as alias
      ##
      set strPromptText to "名前を決めてください" as text
      set strMesText to "名前を決めてください" as text
      ###ファイル名 ダイアログ
      set aliasFilePath to (choose file name strMesText default location aliasContainerDirPath default name strFileName with prompt strPromptText) as «class furl»
      set strFilePath to (POSIX path of aliasFilePath) as text
      set ocidFilePathStr to refMe's NSString's stringWithString:(strFilePath)
      set ocidReturnFilePath to ocidFilePathStr's stringByStandardizingPath()
    else if "処理を中止する" is equal to (button returned of objResponse) then
return "処理を中止しました"
    else
return "エラーしました"
      error number -128
    end if
  else if boolExists = false then
log "そのままファイル生成"
    set ocidReturnFilePath to ocidArgFilePath
  end if
return ocidReturnFilePath
  
end doChkExists

|

quoted form と quote


【スクリプトエディタで開く】|

# APOSTROPHE
set strText to (quoted form of "サンプル") as string
log strText
-->(*'サンプル'*)

set strText to ("'" & "サンプル" & "'") as string
log strText
-->(*'サンプル'*)

# QUOTATION MARK
set strText to (quote & "サンプル" & quote) as string
log strText
-->(*"サンプル"*)

set strText to ("\"" & "サンプル" & "\"") as string
log strText
-->(*"サンプル"*)



|

[as alias list]選択中のファイル・フォルダのUNIXパス


tell application "Finder"

  ####Finderで選択中のアイテムのエリアスのリスト

  set listFinderSelection to selection as alias list

end tell

###クリップボードに入れる値の初期化

set strPathList to "" as text

###リストの数だけ繰り返し

repeat with itemFinderSelection in listFinderSelection

  ###エリアスで確定

  set aliasFinderSelection to itemFinderSelection as alias

  ###UNIXパスにする

  set strfilePath to (get POSIX path of itemFinderSelection)

  ###テキストで格納

  set strPathList to strPathList & strfilePath & "\r" as text

end repeat

###クリップボードに格納

set the clipboard to strPathList

log strPathList



|

[Basic]class «class furl» 実体が無くてもエラーにならないエリアス

Alias形式のパスなんですが
実体が無くてもエラーにならない仕様です。
保存先のパス等、先に決めておきたい場合に便利です

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
#
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
##自分環境がos12なので2.8にしているだけです
use AppleScript version "2.8"
use framework "Foundation"
use scripting additions

property refMe : a reference to current application
property refNSString : a reference to refMe's NSString
property refNSURL : a reference to refMe's NSURL


set PayloadDisplayName to "com.apple.loginwindow"


set strRelativePath to ("~/Desktop/") as text
set ocidRelativePath to refNSString's stringWithString:strRelativePath
set ocidFullPath to ocidRelativePath's stringByStandardizingPath()
set ocidFullPathURL to refMe's NSURL's fileURLWithPath:ocidFullPath
set aliasFullPathURL to ocidFullPathURL as alias

set strFileName to ("" & PayloadDisplayName & ".mobileconfig") as text

set aliasSaveFilePath to choose file name with prompt "ファイル名を付けてください" default name strFileName default location (aliasFullPathURL)
log aliasSaveFilePath as «class furl»
-->(*file Macintosh HD:Users::…*)
###実体が無いのにエラーにならない
log aliasSaveFilePath as alias
-->
error "file \"Macintosh HD:Users:…\"のタイプをaliasに変換できません。" number -1700 from file "Macintosh HD:Users:…" to alias
#実体が無いのでエラーになる

|

[delay]一定期間経過後にアプリケーションを終了する

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
#
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
##自分環境がos12なので2.8にしているだけです
use AppleScript version "2.8"
use framework "Foundation"
use scripting additions

######ログ表示
doLogView()

property objMe : a reference to current application

set recordReturn to display dialog "選択したアプリケーションをX分後に終了します" default answer "60"
log recordReturn

set numMin to text returned of recordReturn as number
log numMin as number

set aliasAppDir to path to applications folder from local domain as alias
log aliasAppDir

set aliasAppPath to choose file with prompt "アプリケーションを選んでください" default location aliasAppDir
log aliasAppPath as alias


set numSec to 60 * numMin as number
log numSec as number

delay numSec

tell application "Finder"
set strShortName to short name of (info for aliasAppPath) as text
end tell

tell application strShortName to quit



#########################ログ表示
to doLogView()

tell application "System Events"
set listAppList to title of (every process where background only is false)
end tell
repeat with objAppList in listAppList
set strAppList to objAppList as text
if strAppList is "スクリプトエディタ" then
tell application "Script Editor"
if frontmost is true then
try
tell application "System Events" to click menu item "ログを表示" of menu "表示" of menu bar item "表示" of menu bar 1 of application process "Script Editor"
end try
end if
end tell
end if
end repeat

end doLogView
#########################

|

[NSURL]Uniform Type Identifier(UTI)の取得

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
#
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
##自分環境がos12なので2.8にしているだけです
use AppleScript version "2.8"
use framework "Foundation"
use scripting additions

######ログ表示
doLogView()

property objMe : a reference to current application
property objNSString : a reference to objMe's NSString
property objNSURL : a reference to objMe's NSURL



property objNSNotFound : a reference to 9.22337203685477E+18 + 5807


set aliasFilePath to (choose file) as alias
log aliasFilePath as alias
log class of aliasFilePath

set strFilePath to POSIX path of aliasFilePath as text
log strFilePath as text
log class of strFilePath

set ocidFileNsUrl to objNSURL's fileURLWithPath:strFilePath
log ocidFileNsUrl as text
log ocidFileNsUrl's className() as text

set {boolResult, ocidContentType} to ocidFileNsUrl's getResourceValue:(reference) forKey:(objMe's NSURLContentTypeKey) |error|:(missing value)

if ocidContentType is not (missing value) then
log ocidContentType's className() as text
###ここにUTIが入ります
set strUTItype to ocidContentType's identifier as text
log strUTItype as text
end if


#########################ログ表示
to doLogView()

tell application "System Events"
set listAppList to title of (every process where background only is false)
end tell
repeat with objAppList in listAppList
set strAppList to objAppList as text
if strAppList is "スクリプトエディタ" then
tell application "Script Editor"
if frontmost is true then
try
tell application "System Events" to click menu item "ログを表示" of menu "表示" of menu bar item "表示" of menu bar 1 of application process "Script Editor"
end try
end if
end tell
end if
end repeat

end doLogView
#########################

|

[Basic]rest of characters log rest of words

set strText to "ABCD EFGH" as text

###1文字目を削除
log rest of characters of strText

###1ワード名を削除
log rest of words of strText

###逆順
log reverse of characters of strText

###取り出し
log characters 1 thru 2 of strText

###取り出し
log text 1 thru 2 of strText

|

[Basic]MimeTypeとUTI

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
#
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
use AppleScript version "2.8"
use framework "Foundation"
use scripting additions
use framework "UniformTypeIdentifiers"


property objMe : a reference to current application
property objNSString : a reference to objMe's NSString
property objNSURL : a reference to objMe's NSURL
property objUTType : a reference to objMe's UTType


####ダイアログで使うデフォルトロケーション
tell application "Finder"
set aliasDefaultLocation to container of (path to me) as alias
##set aliasDefaultLocation to (path to desktop folder from user domain) as alias
end tell
####MIMEリスト
set listMimeType to {"image/jpeg", "image/png", "image/webp", "image/heic", "image/bmp"}

####UTIリスト
set listUTI to {"public.jpeg", "public.png", "public.webp", "public.heic", "public.bmp"}

####ダイアログを出す
set aliasFilePath to (choose file with prompt "ファイルを選んでください" default location (aliasDefaultLocation) of type listUTI with invisibles and showing package contents without multiple selections allowed) as alias

####ファイルのインフォメーションを取得
set objInfoFor to info for aliasFilePath
tell objInfoFor
###UTIを取得
set strTypeIdentifier to type identifier as text
###拡張子を取得
set strExtension to name extension as text
end tell

####拡張子からUTI取得
set ocidUTType to objUTType's typeWithFilenameExtension:strExtension
set strUTI to ocidUTType's identifier as text

####UTIからMIME取得
set ocidFileMimeType to ocidUTType's preferredMIMEType()
set strFileMimeType to ocidFileMimeType as text

####MIMEリストを順番に
repeat with objMimeType in listMimeType
set strMimeType to objMimeType as text
####リストの項目と照合
if strFileMimeType is strMimeType then
log strMimeType & "である"
else
log strMimeType & "これではない"
end if
end repeat

|

[text]文字列の基本

#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
#
#
# com.cocolog-nifty.quicktimer.icefloe
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
##自分環境がos12なので2.8にしているだけです
use AppleScript version "2.8"
use framework "Foundation"
use scripting additions

######ログ表示
doLogView()

############################

set strSampleText to "12345678901234567890" as text

############################
### characterを使う
####7番目の文字
log seventh character of strSampleText

log 7th character of strSampleText

log item 7 of (every character of strSampleText)

log seventh item of (every character of strSampleText)

log 7th item of (every character of strSampleText)

log 19th character of strSampleText

#### itemを使う
####7番目のアイテム
log item 7 of strSampleText

log seventh item of strSampleText

log 7th item of strSampleText

log item 7 of (every item of strSampleText)

log seventh item of (every item of strSampleText)

log 7th item of (every item of strSampleText)

log 19th item of strSampleText


############################

####3文字目から7文字目まで
log characters 3 thru 7 of strSampleText as list

log characters 3 thru 7 of strSampleText as string

log characters 3 thru 7 of strSampleText as text

####3文字目から7文字目まで
log items 3 thru 7 of strSampleText as list

log items 3 thru 7 of strSampleText as string

log items 3 thru 7 of strSampleText as text

############################

####7文字目から最後まで
log characters 7 thru end of strSampleText as list

log characters 7 thru end of strSampleText as string

log characters 7 thru end of strSampleText as text

####7文字目から最後まで
log items 7 thru end of strSampleText as list

log items 7 thru end of strSampleText as string

log items 7 thru end of strSampleText as text

############################
####数える

log length of strSampleText

log number of strSampleText

log (count of strSampleText)



to doLogView()
#########################ログ表示
tell application "System Events"
set listAppList to title of (every process where background only is false)
end tell
repeat with objAppList in listAppList
set strAppList to objAppList as text
if strAppList is "スクリプトエディタ" then
tell application "Script Editor"
if frontmost is true then
try
tell application "System Events" to click menu item "ログを表示" of menu "表示" of menu bar item "表示" of menu bar 1 of application process "Script Editor"
end try
end if
end tell
end if
end repeat
#########################
end doLogView

|

その他のカテゴリー

Accessibility Acrobat Acrobat 2020 Acrobat AddOn Acrobat Annotation Acrobat ARMDC Acrobat AV2 Acrobat BookMark Acrobat Classic Acrobat DC Acrobat Dialog Acrobat Distiller Acrobat Form Acrobat JS Acrobat Manifest Acrobat Menu Acrobat Open Acrobat Plugin Acrobat Preferences Acrobat Preflight Acrobat python Acrobat Reader Acrobat SCA Acrobat SCA Updater Acrobat Sequ Acrobat Sign Acrobat Stamps Acrobat Watermark Acrobat Windows Acrobat Windows Reader Admin Admin Account Admin Apachectl Admin configCode Admin Device Management Admin LaunchServices Admin Locationd Admin loginitem Admin Maintenance Admin Mobileconfig Admin Permission Admin Pkg Admin Power Management Admin Printer Admin SetUp Admin SMB Admin Support Admin System Information Admin Tools Admin Users Admin Volumes Adobe Adobe FDKO Adobe RemoteUpdateManager AppKit Apple AppleScript AppleScript do shell script AppleScript List AppleScript ObjC AppleScript Osax AppleScript PDF AppleScript Pictures AppleScript record AppleScript Script Editor AppleScript Script Menu AppleScript Shortcuts AppleScript Shortcuts Events AppleScript System Events AppleScript System Events Plist AppleScript Video Applications AppStore Archive Attributes Automator BackUp Barcode Barcode QR Barcode QR Decode Bash Basic Basic Path Bluetooth BOX Browser Calendar CD/DVD Choose Chrome CIImage CityCode CloudStorage Color com.apple.LaunchServices.OpenWith Console Contacts CotEditor CURL current application Date&Time delimiters Desktop Device Diff Disk Dock DropBox Droplet eMail Encode % Encode Decode Encode UTF8 Error EXIFData ffmpeg File Finder Firefox Folder FolderAction Fonts GIF github Guide HTML HTML Entity Icon Illustrator Image Events Image2PDF ImageOptim iPhone iWork Javascript Jedit Json Label Leading Zero List locationd LRC lsappinfo LSSharedFileList m3u8 Mail MakePDF Map Math Media Media AVAsset Media AVconvert Media AVFoundation Media AVURLAsset Media Movie Media Music Memo Messages Microsoft Microsoft Edge Microsoft Excel Mouse Music NetWork Notes NSArray NSArray Sort NSBezierPath NSBitmapImageRep NSBundle NSCFBoolean NSCharacterSet NSColor NSColorList NSData NSDecimalNumber NSDictionary NSError NSEvent NSFileAttributes NSFileManager NSFileManager enumeratorAtURL NSFont NSFontManager NSGraphicsContext NSImage NSIndex NSKeyedArchiver NSKeyedUnarchiver NSLocale NSMutableArray NSMutableDictionary NSMutableString NSNotFound NSNumber NSOpenPanel NSPasteboard NSpoint NSPredicate NSPrintOperation NSRange NSRect NSRegularExpression NSRunningApplication NSScreen NSSize NSString NSString stringByApplyingTransform NSStringCompareOptions NSTask NSTimeZone NSURL NSURL File NSURLBookmark NSURLComponents NSURLResourceKey NSURLSession NSUserDefaults NSUUID NSView NSWorkspace Numbers OAuth OneDrive PDF PDFAnnotation PDFAnnotationWidget PDFContext PDFDisplayBox PDFDocumentPermissions PDFImageRep PDFKit PDFnUP PDFOutline perl Photoshop PlistBuddy pluginkit postalcode PostScript prefPane Preview Python QuickLook QuickTime ReadMe Regular Expression Reminders ReName Repeat RTF Safari SaveFile ScreenCapture ScreenSaver SF Symbols character id SF Symbols Entity sips Skype Slack Sound Spotlight sqlite SRT StandardAdditions Swift System Settings TCC TemporaryItems Terminal Text Text CSV Text MD Text TSV TextEdit Tools Translate Trash Twitter Typography UI Unit Conversion UTType valueForKeyPath Video VisionKit Visual Studio Code Wacom webarchive webp Wifi Windows XML XML EPUB XML OPML XML Plist XML RSS XML savedSearch XML SVG XML TTML XML webloc XML XMP YouTube zoom