NSArray Sort

CSVで列指定ソート

202503280555561_1638x1084
NSComparatorを使えないので苦肉の策
ソートの優先順位を自由に変更できるので
今後使っていこうかな


ダウンロード - sort2csv40index.zip



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

001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003(* 
004【前提条件】
005CSVファイルはダブルクオテーション無し
006UTF8で作成されていること
007項目の値にカンマが含まれていないこと
008
009com.cocolog-nifty.quicktimer.icefloe   *)
010----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
011use AppleScript version "2.8"
012use framework "Foundation"
013use framework "AppKit"
014use scripting additions
015property refMe : a reference to current application
016
017##########################
018#何列目の値でソートする?
019set numSortRowNo to 6 as integer
020#1行目は表題?
021set boolFirstLine to true as boolean
022
023##########################
024#
025set aliasPathToMe to (path to me) as alias
026tell application "Finder"
027   set aliasContainerDirPath to (container of aliasPathToMe) as alias
028   set aliasFilePath to (file "擬似住所録.csv" of folder aliasContainerDirPath) as alias
029end tell
030set strFilePath to (POSIX path of aliasFilePath) as text
031set ocidFilePathStr to refMe's NSString's stringWithString:(strFilePath)
032set ocidFilePath to ocidFilePathStr's stringByStandardizingPath()
033set ocidFilePathURL to refMe's NSURL's alloc()'s initFileURLWithPath:(ocidFilePath) isDirectory:(false)
034set strExtensionName to ocidFilePathURL's pathExtension() as text
035#拡張子を取って
036set ocidBaseFilePathURL to ocidFilePathURL's URLByDeletingPathExtension()
037set strSaveExtension to ("ソート済." & strExtensionName & "") as text
038set ocidSaveFilePathURL to ocidBaseFilePathURL's URLByAppendingPathExtension:(strSaveExtension)
039##########################
040#テキスト読み込み
041set listReadStrings to refMe's NSString's alloc()'s initWithContentsOfURL:(ocidFilePathURL) encoding:(refMe's NSUTF8StringEncoding) |error|:(reference)
042set ocidReadStrings to (item 1 of listReadStrings)
043#改行をUNIXに強制
044set ocidReadStrings to (ocidReadStrings's stringByReplacingOccurrencesOfString:("\r\n") withString:("\n"))
045set ocidReadStrings to (ocidReadStrings's stringByReplacingOccurrencesOfString:("\r") withString:("\n"))
046set ocidReadStrings to (ocidReadStrings's stringByReplacingOccurrencesOfString:("\n\n") withString:("\n"))
047#タブは除去しておく
048set ocidReadStrings to (ocidReadStrings's stringByReplacingOccurrencesOfString:("\t") withString:(""))
049#改行終わりをチェック
050#改行終わりのテキストをArrayにすると最後の項目が空になるので
051#エラー対応
052set boolLastChar to ocidReadStrings's hasSuffix:("\n")
053if boolLastChar is true then
054   set numLastChar to 2
055else if boolLastChar is false then
056   set numLastChar to 1
057end if
058##########################
059#ソートに使うDICTの初期化
060set ocidLineDict to refMe's NSMutableDictionary's alloc()'s init()
061#改行でARRAY
062set ocidLineArray to ocidReadStrings's componentsSeparatedByString:("\n")
063set numCntArray to ocidLineArray's |count|()
064#1行目を飛ばすか?
065if boolFirstLine is true then
066   #1行目を確保しておく
067   set ocidFirstLine to ocidLineArray's firstObject()
068   set numStartNo to 1 as integer
069else if boolFirstLine is false then
070   set numStartNo to 0 as integer
071end if
072#全行巡回
073repeat with itemLineNo from numStartNo to (numCntArray - numLastChar) by 1
074   set ocidLineString to (ocidLineArray's objectAtIndex:(itemLineNo))
075   #行を区切り文字でArrayにして
076   set ocidItemsArray to (ocidLineString's componentsSeparatedByString:(","))
077   #検索対象を取り出して
078   set ocidSortKey to (ocidItemsArray's objectAtIndex:(numSortRowNo - 1))
079   #Arrayの最初の項目に入れます
080   (ocidItemsArray's insertObject:(ocidSortKey) atIndex:(0))
081   #テキストにしてこれをキーにします
082   set ocidKeyText to (ocidItemsArray's componentsJoinedByString:(""))
083   #↑をキーに Valueは行テキストのDICTにします
084   set ocidKeyDict to refMe's NSMutableDictionary's alloc()'s init()
085   (ocidLineDict's setValue:(ocidLineString) forKey:(ocidKeyText))
086end repeat
087
088##########################
089#キーのソート(方法は要カスタマイズ)
090set ocidAllKeys to ocidLineDict's allKeys()
091
092#ソート
093set ocidDescriptor to refMe's NSSortDescriptor's sortDescriptorWithKey:("self") ascending:(yes) selector:("localizedStandardCompare:")
094set ocidDescriptorArray to refMe's NSArray's arrayWithObject:(ocidDescriptor)
095set ocidSortedKeyArray to ocidAllKeys's sortedArrayUsingDescriptors:(ocidDescriptorArray)
096
097##########################
098#ソート後のテキスト
099set ocidOutputArray to refMe's NSMutableArray's alloc()'s init()
100if boolFirstLine is true then
101   #1行目を戻す
102   ocidOutputArray's addObject:(ocidFirstLine)
103end if
104#ソート済みのキーを順に処理
105repeat with itemSortedKey in ocidSortedKeyArray
106   #値=行テキストを取り出します
107   set ocidListStringValue to (ocidLineDict's objectForKey:(itemSortedKey))
108   #値を出力用のArrayに入れて
109   (ocidOutputArray's addObject:(ocidListStringValue))
110end repeat
111
112##########################
113#UNIX改行でテキストに戻す
114set ocidJoinText to ocidOutputArray's componentsJoinedByString:("\n")
115
116##########################
117#保存
118set listDone to ocidJoinText's writeToURL:(ocidSaveFilePathURL) atomically:(true) encoding:(refMe's NSUTF8StringEncoding) |error|:(reference)
119if (item 1 of listDone) is true then
120   return "正常終了"
121else if (item 1 of listDone) is false then
122   log (item 2 of listDone)'s localizedDescription() as text
123   return "保存に失敗しました"
124end if
125

| | コメント (0)

[NSArray]逆順に並び替え ソートする

NSArray逆順ソート.scpt

AppleScript サンプルコード

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

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003#com.cocolog-nifty.quicktimer.icefloe
004----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
005use AppleScript version "2.8"
006use framework "Foundation"
007use framework "AppKit"
008use scripting additions
009property refMe : a reference to current application
010
011
012set listSample to {"A", "B", "C", "", "D", "E", "F"} as list
013
014#Arrayにして
015set ocidSampleArray to refMe's NSArray's arrayWithArray:(listSample)
016
017#NSPredicateで空項目削除を定義
018set appPredicate to refMe's NSPredicate's predicateWithFormat_("SELF != '' AND SELF != ' ' AND SELF != %@", (refMe's NSNull's |null|()))
019
020#空項目削除
021set ocidFilteredArray to ocidSampleArray's filteredArrayUsingPredicate:(appPredicate)
022
023log ocidFilteredArray as list
024-->(*A, B, C, D, E, F*)
025
026
027###########
028#sortedArrayUsingSelectorで普通にソートして
029set ocidSortedArray to ocidFilteredArray's sortedArrayUsingSelector:("localizedStandardCompare:")
030
031#NSEnumeratorに渡して 逆順にしてもらう
032set ocidEnuArray to ocidSortedArray's reverseObjectEnumerator()
033
034#逆順になったEnumeratorをそのまま全部で逆順リスト
035set ocidReverseArray to ocidEnuArray's allObjects()
036
037
038
039log ocidReverseArray as list
040-->(*F, E, D, C, B, A*)
041
AppleScriptで生成しました

|

[Enumerator]逆順にソートする


AppleScript サンプルコード

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

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003# com.cocolog-nifty.quicktimer.icefloe
004#
005#
006----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
007use AppleScript version "2.8"
008use framework "Foundation"
009use scripting additions
010
011property refMe : a reference to current application
012
013#リスト形式
014set listNO to {11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10} as list
015
016#Arrayにして
017set ocidNoArray to refMe's NSArray's arrayWithArray:(listNO)
018
019#まずは正順にソートして
020set ocidSortedArray to ocidNoArray's sortedArrayUsingSelector:("compare:")
021
022#逆順列挙して
023set ocidReverseEnumeratorArray to ocidSortedArray's reverseObjectEnumerator()
024
025#取り出す
026set ocidReverseArray to ocidReverseEnumeratorArray's allObjects()
027
028log ocidReverseArray as list
029-->(*20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1*)
AppleScriptで生成しました

|

[NSArray]ソート 2種

【A】sortedArrayUsingDescriptors:
複数のソート条件を指定できる 
https://quicktimer.cocolog-nifty.com/icefloe/2023/09/post-4c46eb.html

【B】sortedArrayUsingSelector:
特定の条件にあわせてソートできる 簡単
https://quicktimer.cocolog-nifty.com/icefloe/2023/09/post-dae2be.html


【A】sortedArrayUsingDescriptors:({Array})
複数のソート条件を指定できる
Descriptor
sortDescriptorWithKey:ascending:selector:
Sortdescriptorwithkey0021920x108072ppirg


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

#!/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
property refMe : a reference to current application



######【KEY】
(*
■ARRAYの値が 文字列や数値の場合
self
■ARRAYの値が NSURLなら
absoluteString
host
path
lastPathComponent 等が利用できます
■ARRAYの値が DICTなら
dictのKEYを利用できる
*)
##一般的なARRAYの場合は self 一択
set listForArray to {"東京", "神奈川", "千葉", "埼玉", "茨城", "群馬", "AA", "bb", "aa", "1234"} as list
set ocidArrayM to refMe's NSMutableArray's arrayWithArray:(listForArray)
set ocidDescriptor to refMe's NSSortDescriptor's sortDescriptorWithKey:("self") ascending:(yes) selector:"localizedStandardCompare:"
set ocidDescriptorArray to refMe's NSArray's arrayWithObject:(ocidDescriptor)
set ocidSortedArray to ocidArrayM's sortedArrayUsingDescriptors:(ocidDescriptorArray)
log ocidSortedArray as list

##NSURLが格納されているArrayの場合
set ocidDirPathStr to refMe's NSString's stringWithString:("/System/Library/Templates/Data/Library/User Pictures/Instruments")
set ocidDirPath to ocidDirPathStr's stringByStandardizingPath()
set ocidDirPathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidDirPath) isDirectory:true)
set appFileManager to refMe's NSFileManager's defaultManager()
set ocidArrayM to appFileManager's contentsOfDirectoryAtURL:(ocidDirPathURL) includingPropertiesForKeys:({(refMe's NSURLPathKey)}) options:(refMe's NSDirectoryEnumerationSkipsHiddenFiles) |error|:(missing value)
##ファイル名(lastPathComponent)でソート
set ocidDescriptor to refMe's NSSortDescriptor's sortDescriptorWithKey:("lastPathComponent") ascending:(yes) selector:"localizedStandardCompare:"
set ocidDescriptorArray to refMe's NSArray's arrayWithObject:(ocidDescriptor)
set ocidSortedArray to ocidArrayM's sortedArrayUsingDescriptors:(ocidDescriptorArray)
log ocidSortedArray as list

set listForArray to {{reg:"東京"}, {reg:"神奈川"}, {reg:"千葉"}, {reg:"埼玉"}, {reg:"茨城"}, {reg:"群馬"}} as list
set ocidArrayM to refMe's NSMutableArray's arrayWithArray:(listForArray)

set ocidDescriptor to refMe's NSSortDescriptor's sortDescriptorWithKey:("reg") ascending:(yes) selector:"localizedStandardCompare:"
set ocidDescriptorArray to refMe's NSArray's arrayWithObject:(ocidDescriptor)
set ocidSortedArray to ocidArrayM's sortedArrayUsingDescriptors:(ocidDescriptorArray)
log ocidSortedArray as list


set listForArray to {"東京", "神奈川", "千葉", "埼玉", "茨城", "群馬", "AA", "bb", "aa", "1234"} as list
set ocidArrayM to refMe's NSMutableArray's arrayWithArray:(listForArray)

######【ascending】
# TRUE YES 正順
# FALSE NO 逆順

set ocidDescriptor to refMe's NSSortDescriptor's sortDescriptorWithKey:("self") ascending:(yes) selector:"localizedStandardCompare:"
set ocidDescriptorArray to refMe's NSArray's arrayWithObject:(ocidDescriptor)
set ocidSortedArray to ocidArrayM's sortedArrayUsingDescriptors:(ocidDescriptorArray)
log ocidSortedArray as list
set ocidDescriptor to refMe's NSSortDescriptor's sortDescriptorWithKey:("self") ascending:(no) selector:"localizedStandardCompare:"
set ocidDescriptorArray to refMe's NSArray's arrayWithObject:(ocidDescriptor)
set ocidSortedArray to ocidArrayM's sortedArrayUsingDescriptors:(ocidDescriptorArray)
log ocidSortedArray as list

######【selector】
(*
漢字が入るなら通常これ
localizedStandardCompare
英数小文字を『先』
compare
localizedCompare
英数大文字小文字判定しない
caseInsensitiveCompare
localizedCaseInsensitiveCompare
*)
set ocidDescriptor to refMe's NSSortDescriptor's sortDescriptorWithKey:("self") ascending:(yes) selector:"localizedStandardCompare:"
set ocidDescriptorArray to refMe's NSArray's arrayWithObject:(ocidDescriptor)
set ocidSortedArray to ocidArrayM's sortedArrayUsingDescriptors:(ocidDescriptorArray)
log ocidSortedArray as list
set ocidDescriptor to refMe's NSSortDescriptor's sortDescriptorWithKey:("self") ascending:(yes) selector:"compare:"
set ocidDescriptorArray to refMe's NSArray's arrayWithObject:(ocidDescriptor)
set ocidSortedArray to ocidArrayM's sortedArrayUsingDescriptors:(ocidDescriptorArray)
log ocidSortedArray as list
set ocidDescriptor to refMe's NSSortDescriptor's sortDescriptorWithKey:("self") ascending:(yes) selector:"localizedCompare:"
set ocidDescriptorArray to refMe's NSArray's arrayWithObject:(ocidDescriptor)
set ocidSortedArray to ocidArrayM's sortedArrayUsingDescriptors:(ocidDescriptorArray)
log ocidSortedArray as list
set ocidDescriptor to refMe's NSSortDescriptor's sortDescriptorWithKey:("self") ascending:(yes) selector:"caseInsensitiveCompare:"
set ocidDescriptorArray to refMe's NSArray's arrayWithObject:(ocidDescriptor)
set ocidSortedArray to ocidArrayM's sortedArrayUsingDescriptors:(ocidDescriptorArray)
log ocidSortedArray as list
set ocidDescriptor to refMe's NSSortDescriptor's sortDescriptorWithKey:("self") ascending:(yes) selector:"localizedCaseInsensitiveCompare:"
set ocidDescriptorArray to refMe's NSArray's arrayWithObject:(ocidDescriptor)
set ocidSortedArray to ocidArrayM's sortedArrayUsingDescriptors:(ocidDescriptorArray)
log ocidSortedArray as list

【B】sortedArrayUsingSelector:
特定の条件にあわせてソートできる



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

#!/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
property refMe : a reference to current application

set listForArray to {"東京", "神奈川", "千葉", "埼玉", "茨城", "群馬", "AA", "bb", "aa", "1234"} as list

set ocidArrayM to refMe's NSMutableArray's arrayWithArray:(listForArray)

#######漢字が入るなら通常これ
set ocidSortedArray to ocidArrayM's sortedArrayUsingSelector:("localizedStandardCompare:")
log ocidSortedArray as list
#######英数小文字を『先』なら
set ocidSortedArray to ocidArrayM's sortedArrayUsingSelector:("compare:")
log ocidSortedArray as list
set ocidSortedArray to ocidArrayM's sortedArrayUsingSelector:("localizedCompare:")
log ocidSortedArray as list
#######英数大文字小文字判定しない
set ocidSortedArray to ocidArrayM's sortedArrayUsingSelector:("caseInsensitiveCompare:")
log ocidSortedArray as list
set ocidSortedArray to ocidArrayM's sortedArrayUsingSelector:("localizedCaseInsensitiveCompare:")
log ocidSortedArray as list

|

【A】sortedArrayUsingDescriptors:

【A】sortedArrayUsingDescriptors:({Array}) 複数のソート条件を指定できる Descriptor sortDescriptorWithKey:ascending:selector: Sortdescriptorwithkey0021920x108072ppirg

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

#!/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
property refMe : a reference to current application



######【KEY】
(*
■ARRAYの値が 文字列や数値の場合
self
■ARRAYの値が NSURLなら
absoluteString
host
path
lastPathComponent 等が利用できます
■ARRAYの値が DICTなら
dictのKEYを利用できる
*)
##一般的なARRAYの場合は self 一択
set listForArray to {"東京", "神奈川", "千葉", "埼玉", "茨城", "群馬", "AA", "bb", "aa", "1234"} as list
set ocidArrayM to refMe's NSMutableArray's arrayWithArray:(listForArray)
set ocidDescriptor to refMe's NSSortDescriptor's sortDescriptorWithKey:("self") ascending:(yes) selector:"localizedStandardCompare:"
set ocidDescriptorArray to refMe's NSArray's arrayWithObject:(ocidDescriptor)
set ocidSortedArray to ocidArrayM's sortedArrayUsingDescriptors:(ocidDescriptorArray)
log ocidSortedArray as list

##NSURLが格納されているArrayの場合
set ocidDirPathStr to refMe's NSString's stringWithString:("/System/Library/Templates/Data/Library/User Pictures/Instruments")
set ocidDirPath to ocidDirPathStr's stringByStandardizingPath()
set ocidDirPathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidDirPath) isDirectory:true)
set appFileManager to refMe's NSFileManager's defaultManager()
set ocidArrayM to appFileManager's contentsOfDirectoryAtURL:(ocidDirPathURL) includingPropertiesForKeys:({(refMe's NSURLPathKey)}) options:(refMe's NSDirectoryEnumerationSkipsHiddenFiles) |error|:(missing value)
##ファイル名(lastPathComponent)でソート
set ocidDescriptor to refMe's NSSortDescriptor's sortDescriptorWithKey:("lastPathComponent") ascending:(yes) selector:"localizedStandardCompare:"
set ocidDescriptorArray to refMe's NSArray's arrayWithObject:(ocidDescriptor)
set ocidSortedArray to ocidArrayM's sortedArrayUsingDescriptors:(ocidDescriptorArray)
log ocidSortedArray as list

set listForArray to {{reg:"東京"}, {reg:"神奈川"}, {reg:"千葉"}, {reg:"埼玉"}, {reg:"茨城"}, {reg:"群馬"}} as list
set ocidArrayM to refMe's NSMutableArray's arrayWithArray:(listForArray)

set ocidDescriptor to refMe's NSSortDescriptor's sortDescriptorWithKey:("reg") ascending:(yes) selector:"localizedStandardCompare:"
set ocidDescriptorArray to refMe's NSArray's arrayWithObject:(ocidDescriptor)
set ocidSortedArray to ocidArrayM's sortedArrayUsingDescriptors:(ocidDescriptorArray)
log ocidSortedArray as list


set listForArray to {"東京", "神奈川", "千葉", "埼玉", "茨城", "群馬", "AA", "bb", "aa", "1234"} as list
set ocidArrayM to refMe's NSMutableArray's arrayWithArray:(listForArray)

######【ascending】
# TRUE YES 正順
# FALSE NO 逆順

set ocidDescriptor to refMe's NSSortDescriptor's sortDescriptorWithKey:("self") ascending:(yes) selector:"localizedStandardCompare:"
set ocidDescriptorArray to refMe's NSArray's arrayWithObject:(ocidDescriptor)
set ocidSortedArray to ocidArrayM's sortedArrayUsingDescriptors:(ocidDescriptorArray)
log ocidSortedArray as list
set ocidDescriptor to refMe's NSSortDescriptor's sortDescriptorWithKey:("self") ascending:(no) selector:"localizedStandardCompare:"
set ocidDescriptorArray to refMe's NSArray's arrayWithObject:(ocidDescriptor)
set ocidSortedArray to ocidArrayM's sortedArrayUsingDescriptors:(ocidDescriptorArray)
log ocidSortedArray as list

######【selector】
(*
漢字が入るなら通常これ
localizedStandardCompare
英数小文字を『先』
compare
localizedCompare
英数大文字小文字判定しない
caseInsensitiveCompare
localizedCaseInsensitiveCompare
*)
set ocidDescriptor to refMe's NSSortDescriptor's sortDescriptorWithKey:("self") ascending:(yes) selector:"localizedStandardCompare:"
set ocidDescriptorArray to refMe's NSArray's arrayWithObject:(ocidDescriptor)
set ocidSortedArray to ocidArrayM's sortedArrayUsingDescriptors:(ocidDescriptorArray)
log ocidSortedArray as list
set ocidDescriptor to refMe's NSSortDescriptor's sortDescriptorWithKey:("self") ascending:(yes) selector:"compare:"
set ocidDescriptorArray to refMe's NSArray's arrayWithObject:(ocidDescriptor)
set ocidSortedArray to ocidArrayM's sortedArrayUsingDescriptors:(ocidDescriptorArray)
log ocidSortedArray as list
set ocidDescriptor to refMe's NSSortDescriptor's sortDescriptorWithKey:("self") ascending:(yes) selector:"localizedCompare:"
set ocidDescriptorArray to refMe's NSArray's arrayWithObject:(ocidDescriptor)
set ocidSortedArray to ocidArrayM's sortedArrayUsingDescriptors:(ocidDescriptorArray)
log ocidSortedArray as list
set ocidDescriptor to refMe's NSSortDescriptor's sortDescriptorWithKey:("self") ascending:(yes) selector:"caseInsensitiveCompare:"
set ocidDescriptorArray to refMe's NSArray's arrayWithObject:(ocidDescriptor)
set ocidSortedArray to ocidArrayM's sortedArrayUsingDescriptors:(ocidDescriptorArray)
log ocidSortedArray as list
set ocidDescriptor to refMe's NSSortDescriptor's sortDescriptorWithKey:("self") ascending:(yes) selector:"localizedCaseInsensitiveCompare:"
set ocidDescriptorArray to refMe's NSArray's arrayWithObject:(ocidDescriptor)
set ocidSortedArray to ocidArrayM's sortedArrayUsingDescriptors:(ocidDescriptorArray)
log ocidSortedArray as list

|

【B】sortedArrayUsingSelector:

【B】sortedArrayUsingSelector: 特定の条件にあわせてソートできる

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

#!/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
property refMe : a reference to current application

set listForArray to {"東京", "神奈川", "千葉", "埼玉", "茨城", "群馬", "AA", "bb", "aa", "1234"} as list

set ocidArrayM to refMe's NSMutableArray's arrayWithArray:(listForArray)

#######漢字が入るなら通常これ
set ocidSortedArray to ocidArrayM's sortedArrayUsingSelector:("localizedStandardCompare:")
log ocidSortedArray as list
#######英数小文字を『先』なら
set ocidSortedArray to ocidArrayM's sortedArrayUsingSelector:("compare:")
log ocidSortedArray as list
set ocidSortedArray to ocidArrayM's sortedArrayUsingSelector:("localizedCompare:")
log ocidSortedArray as list
#######英数大文字小文字判定しない
set ocidSortedArray to ocidArrayM's sortedArrayUsingSelector:("caseInsensitiveCompare:")
log ocidSortedArray as list
set ocidSortedArray to ocidArrayM's sortedArrayUsingSelector:("localizedCaseInsensitiveCompare:")
log ocidSortedArray as list

|

sortDescriptorWithKey:ascending:

Sortdescriptorwithkey0011920x108072ppirgSortdescriptorwithkey0021920x108072ppirg

|

[SORT]ファイルパスリストからファイル名の重複を調べる

#/bin/sh

find $HOME/Music  -type f -iname "*.mp3" >> ~/Desktop/FileList.txt

find $HOME/Music  -type f -iname "*.m4a" >> ~/Desktop/FileList.txt


とか で ファイルリスト出した時用


#!/usr/bin/env osascript
----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
#
#
(*

find $HOME/Music -type f -iname "*.mp3" >> ~/Desktop/FileList.txt
find $HOME/Music -type f -iname "*.m4a" >> ~/Desktop/FileList.txt

*)
#
#
# 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 refNSMutableString : a reference to refMe's NSMutableString
property refNSArray : a reference to refMe's NSArray
property refNSMutableArray : a reference to refMe's NSMutableArray
property refNSURL : a reference to refMe's NSURL

property refNSRegularExpression : a reference to refMe's NSRegularExpression
property refNSRegularExpressionSearch : a reference to refMe's NSRegularExpressionSearch
property refNSCharacterSet : a reference to refMe's NSCharacterSet



##############################################
## ダイアログ関連
##############################################
tell application "Finder"
set aliasDefaultLocation to (path to desktop folder from user domain) as alias
end tell
set listChooseFileUTI to {"public.item", "public.text"}
set strPromptText to "ファイルを選んでください" as text
set aliasFilePath to (choose file with prompt strPromptText default location (aliasDefaultLocation) of type listChooseFileUTI without invisibles, multiple selections allowed and showing package contents) as alias

####ファイルパス
set strFilePath to POSIX path of aliasFilePath as text
####ドキュメントのパスをNSString
set ocidFilePath to refNSString's stringWithString:strFilePath
####ドキュメントのパスをNSURL
set ocidFilePathURL to refNSURL's fileURLWithPath:ocidFilePath
###ファイル名
set ocidBaseFilePathURL to ocidFilePathURL's URLByDeletingPathExtension()
###拡張子を取ったベースになるファイル名
set strBaseFileName to (ocidBaseFilePathURL's lastPathComponent()) as text

##############################################
## 保存先 ダイアログ関連
##############################################

set aliasDefaultLocation to (path to desktop folder from user domain) as alias
set strDefaultName to (strBaseFileName & ".output.txt") as text
set strPromptText to "名前を決めてください"

set aliasSaveFilePath to (choose file name default location aliasDefaultLocation default name strDefaultName with prompt strPromptText) as «class furl»
####UNIXパス
set strSaveFilePath to POSIX path of aliasSaveFilePath as text
####ドキュメントのパスをNSString
set ocidSaveFilePath to refNSString's stringWithString:strSaveFilePath
####ドキュメントのパスをNSURL
set ocidSaveFilePathURL to refNSURL's fileURLWithPath:ocidSaveFilePath
###拡張子取得
set strFileExtensionName to ocidSaveFilePathURL's pathExtension() as text
###ダイアログで拡張子を取っちゃった時対策
if strFileExtensionName is not "lrc" then
set ocidSaveFilePathURL to ocidSaveFilePathURL's URLByAppendingPathExtension:"txt"
end if

##############################################
## 読み込んだ内容のテキスト段階での処理
##############################################
####可変テキスト初期化
set ocidReadData to refNSMutableString's alloc()'s initWithCapacity:0
#####読み取ったコンテンツをテキストに格納
set ocidReadData to refNSMutableString's stringWithContentsOfFile:ocidFilePath encoding:(refMe's NSUTF8StringEncoding) |error|:(missing value)
#########パス部分を削除してファイル名のみにする
###レンジを作る
set ocidNsRange to ocidReadData's rangeOfString:ocidReadData
###置き換え
ocidReadData's replaceOccurrencesOfString:"/.*/" withString:("") options:(refNSRegularExpressionSearch) range:ocidNsRange
#########空行があれば削除しておく
###レンジを作る
set ocidNsRange to ocidReadData's rangeOfString:ocidReadData
###置き換え
ocidReadData's replaceOccurrencesOfString:"\n\n" withString:("\n") options:(refNSRegularExpressionSearch) range:ocidNsRange

##############################################
##改行でリスト化する
##############################################
###初期化
set ocidReadDataArray to refNSMutableArray's alloc()'s initWithCapacity:0
####改行を定義
set ocidNewlineCharacterSett to refNSCharacterSet's newlineCharacterSet()
####改行でリスト化
set ocidReadDataArray to ocidReadData's componentsSeparatedByCharactersInSet:ocidNewlineCharacterSett
###初期化
set ocidReadDataArrayM to refNSMutableArray's alloc()'s initWithCapacity:0
###可変リストに格納
ocidReadDataArrayM's addObjectsFromArray:ocidReadDataArray
####読み込んだテキストを解放する
set ocidReadData to "" as text
##############################################
##空のアイテムがあれば削除する
##############################################
set numCntArrayItem to (count of ocidReadDataArrayM) as integer
repeat
####空のオブジェクトがあるか?
set boolContain to (ocidReadDataArrayM's containsObject:"") as boolean
####あれば
if boolContain is true then
####空のオプジェクトのインデクスを調べて
set ocidIndex to (ocidReadDataArrayM's indexOfObject:"") as integer
###削除する
ocidReadDataArrayM's removeObjectAtIndex:ocidIndex
else
####空のオブジェクトが無くなればリピートを抜ける
exit repeat
end if
end repeat

##############################################
##正順に並び替える
##############################################
###初期化
set ocidSortArray to refNSMutableArray's alloc()'s initWithCapacity:0
set ocidSelf to refNSString's stringWithString:"self"
set ocidSortArray to ocidReadDataArrayM's sortedArrayUsingSelector:"localizedCaseInsensitiveCompare:"
####可変リストに格納
set ocidSortedArray to refNSMutableArray's alloc()'s initWithCapacity:0
ocidSortedArray's addObjectsFromArray:ocidSortArray


##############################################
##本処理
##############################################
####リストの数を数える
set numCntArrayData to (count of ocidSortedArray) as integer
####index用の1少ない数
set numCntNo to (numCntArrayData - 1) as integer
####処理は逆順に行う
repeat (numCntArrayData - 1) times
####最後のアイテムを取り出す
set strItemA to (ocidSortedArray's objectAtIndex:numCntNo) as text
####次のアイテムを取り出す
set numCntNextNo to numCntNo - 1 as integer
set strItemB to (ocidSortedArray's objectAtIndex:numCntNextNo) as text
####内容が同じなら
if strItemA is not strItemB then
###逆順処理なので先の項目strItemAを削除する
ocidSortedArray's removeObjectAtIndex:numCntNo
end if
set numCntNo to numCntNo as integer
####最後の行は処理しない(比較相手がない=削除しても良いか)
if numCntNo = 1 then
ocidSortedArray's removeObjectAtIndex:0
exit repeat
end if
set numCntNo to numCntNo - 1 as integer
end repeat

##############################################
##テキスト化する
##############################################
###可変テキストを初期化
set ocidOutPutStrings to refNSMutableString's alloc()'s initWithCapacity:0
###オブジェクト毎に改行を入れたテキストにする
repeat with objMutableArray in ocidSortedArray
(ocidOutPutStrings's appendString:(objMutableArray as text))
log objMutableArray as text
(ocidOutPutStrings's appendString:("\n"))
end repeat


##############################################
##保存
##############################################
set listWritetoUrlArray to ocidOutPutStrings's writeToURL:ocidSaveFilePathURL atomically:true encoding:(refMe's NSUTF8StringEncoding) |error|:(reference)

#####データ部
set boolDone to item 1 of listWritetoUrlArray as boolean
if boolDone is true then
log "終了しました"
else
log "エラーが発生しました"
end if
####エラー部
set ocidNSErrorData to item 2 of listWritetoUrlArray
if ocidNSErrorData is not (missing value) then
doGetErrorData(ocidNSErrorData)
end if


##############################################
## エラー発生時のログ用
##############################################


to doGetErrorData(ocidNSErrorData)
#####個別のエラー情報
log "エラーコード:" & ocidNSErrorData's code() as text
log "エラードメイン:" & ocidNSErrorData's domain() as text
log "Description:" & ocidNSErrorData's localizedDescription() as text
log "FailureReason:" & ocidNSErrorData's localizedFailureReason() as text
log ocidNSErrorData's localizedRecoverySuggestion() as text
log ocidNSErrorData's localizedRecoveryOptions() as text
log ocidNSErrorData's recoveryAttempter() as text
log ocidNSErrorData's helpAnchor() as text
set ocidNSErrorUserInfo to ocidNSErrorData's userInfo()
set ocidAllValues to ocidNSErrorUserInfo's allValues() as list
set ocidAllKeys to ocidNSErrorUserInfo's allKeys() as list
repeat with ocidKeys in ocidAllKeys
if (ocidKeys as text) is "NSUnderlyingError" then
log (ocidNSErrorUserInfo's valueForKey:ocidKeys)'s localizedDescription() as text
log (ocidNSErrorUserInfo's valueForKey:ocidKeys)'s localizedFailureReason() as text
log (ocidNSErrorUserInfo's valueForKey:ocidKeys)'s localizedRecoverySuggestion() as text
log (ocidNSErrorUserInfo's valueForKey:ocidKeys)'s localizedRecoveryOptions() as text
log (ocidNSErrorUserInfo's valueForKey:ocidKeys)'s recoveryAttempter() as text
log (ocidNSErrorUserInfo's valueForKey:ocidKeys)'s helpAnchor() as text
else
####それ以外の値はそのままテキストで読める
log (ocidKeys as text) & ": " & (ocidNSErrorUserInfo's valueForKey:ocidKeys) as text
end if
end repeat

end doGetErrorData

|

[プレビュー]ファイル名順にして開き直す

うーん他に何かいい方法ないんか…

#!/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
property objMe : a reference to current application
property objNSString : a reference to objMe's NSString
property objNSMutableArray : a reference to objMe's NSMutableArray


(*
tell application "Preview"
set listEveryDoc to every document
log "listEveryDoc"
log listEveryDoc
end tell



tell application "Preview"
set listEveryDocName to name of every document
log "name"
log listEveryDocName
end tell

tell application "Preview"
set listEveryDocPath to path of every document
log "path"
log listEveryDocPath
end tell

log listEveryDocPath
*)
######
tell application "Preview"
set listEveryDocPath to path of every document
log "path"
log listEveryDocPath
activate
end tell

if listEveryDocPath is {} then
return "ドキュメントを開いていません"
end if


###可変リストに変更
set ocidNSArrayM to (objNSMutableArray's arrayWithArray:listEveryDocPath)
###並び替え
set ocidSortedArray to (ocidNSArrayM's sortedArrayUsingSelector:"compare:")
###ocidアレイ を リストに変換
set listSortedArray to ocidSortedArray as list

#tell application "Preview"
#activate
#tell application "System Events"
#keystroke "W" using {command down}
#end tell
#end tell
#return

tell application "Preview"
close every document
end tell

tell application "Preview"
tell window 1
####同じウィンドウで
####ファイル名順に開き直す
open listSortedArray
end tell
end tell

|

[valueForKeyPath] pathExtension


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

名称未設定.scpt
ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003(*
004valueForKeyPathpathExtension=拡張子で検索して
005収集します
006
007com.cocolog-nifty.quicktimer.icefloe *)
008----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
009##自分環境がos12なので2.8にしているだけです
010use AppleScript version "2.8"
011use framework "Foundation"
012use framework "AppKit"
013use scripting additions
014property refMe : a reference to current application
015
016
017set appFileManager to refMe's NSFileManager's defaultManager()
018
019try
020   set listAliasDirPath to (choose folder "画像が入っているフォルダを選んでください" with prompt "フォルダを選択してください" default location (path to desktop folder from user domain) with multiple selections allowed without invisibles and showing package contents)
021on error
022   log "エラーしました"
023   return
024end try
025
026######フォルダ毎の処理
027repeat with itemAliasDirPath in listAliasDirPath
028   ###エリアス
029   set aliasAliasDirPath to itemAliasDirPath as alias
030   ###パス
031   set strDirPath to (POSIX path of aliasAliasDirPath) as text
032   ###NSStringテキスト
033   set ocidDirPath to (refMe's NSString's stringWithString:(strDirPath))
034   #####NSURL NSStringURL
035   set ocidUrlPath to (refMe's NSURL's fileURLWithPath:(ocidDirPath))
036   #収集するキー
037   set ocidKeyArray to refMe's NSMutableArray's alloc()'s init()
038   (ocidKeyArray's addObject:(refMe's NSURLIsAliasFileKey))
039   (ocidKeyArray's addObject:(refMe's NSURLIsRegularFileKey))
040   set ocidOption to (refMe's NSDirectoryEnumerationSkipsHiddenFiles)
041   ###フォルダの内容をリストで取得
042   set ocidContentsURLArray to (appFileManager's contentsOfDirectoryAtURL:(ocidUrlPath) includingPropertiesForKeys:(ocidKeyArray) options:(ocidOption) |error|:(missing value))
043   ###可変リストに変更
044   set ocidContentsURLArrayM to (refMe's NSMutableArray's arrayWithArray:ocidContentsURLArray)
045   ###ファイルパスリストに変更
046   set ocidExtensionArray to (ocidContentsURLArrayM's valueForKeyPath:"pathExtension")
047   ###並び変わった順
048   repeat with itemExtensionName in ocidExtensionArray
049      log itemExtensionName as text
050      --->>ここに順番に処理する操作等を記述する
051   end repeat
052   (*png*)
053   (*png*)
054   (*png*)
055   (*png*)
056   (*png*)
057   (*png*)
058   (*png*)
059   (*png*)
060   (*png*)
061   (*png*)
062   
063end repeat
AppleScriptで生成しました

#!/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 objMe : a reference to current application
property objNSString : a reference to objMe's NSString
property objNSURL : a reference to objMe's NSURL

property objNSArray : a reference to objMe's NSArray
property objNSMutableArray : a reference to objMe's NSMutableArray

set objFileManager to objMe's NSFileManager's defaultManager()

#####
set ocidNSURLIsAliasFileKey to objMe's NSURLIsAliasFileKey
set ocidNSURLIsRegularFileKey to objMe's NSURLIsRegularFileKey
set ocidNSURLFileSizeKey to objMe's NSURLFileSizeKey
#####

try
set listAliasDir to (choose folder "画像が入っているフォルダを選んでください" with prompt "フォルダを選択してください" default location (path to desktop folder from user domain) with multiple selections allowed without invisibles and showing package contents)
on error
log "エラーしました"
return
end try


######フォルダ毎の処理
repeat with objAliasDir in listAliasDir

###エリアス
set aliasAliasDir to objAliasDir as alias
###パス
set strDirPath to POSIX path of aliasAliasDir as text
###NSStringテキスト
set ocidDirPath to (objNSString's stringWithString:strDirPath)
#####NSURL NSStringURL
set ocidUrlPath to (objNSURL's fileURLWithPath:ocidDirPath)
###フォルダの内容をリストで取得
set objContentsArray to (objFileManager's contentsOfDirectoryAtURL:ocidUrlPath includingPropertiesForKeys:{ocidNSURLIsAliasFileKey} options:(4) |error|:(missing value))
###可変リストに変更
set ocidNSArrayM to (objNSMutableArray's arrayWithArray:objContentsArray)
###ファイルパスリストに変更
set ocidNSArrayMpath to (ocidNSArrayM's valueForKeyPath:"pathExtension")
###並び替え
set ocidSortedArray to (ocidNSArrayMpath's sortedArrayUsingSelector:"compare:")
log ocidSortedArray's className() as text
log ocidSortedArray as list
###並び変わった順
repeat with objSortedArray in ocidSortedArray
log objSortedArray as text
--->>ここに順番に処理する操作等を記述する
end repeat
(*png*)
(*png*)
(*png*)
(*png*)
(*png*)
(*png*)
(*png*)
(*png*)
(*png*)
(*png*)

end repeat

|

その他のカテゴリー

Accessibility Acrobat Acrobat 2020 Acrobat 2024 Acrobat AddOn Acrobat Annotation Acrobat AppleScript Acrobat ARMDC Acrobat AV2 Acrobat BookMark Acrobat Classic Acrobat DC Acrobat Dialog Acrobat Distiller Acrobat Form Acrobat GentechAI Acrobat JS Acrobat JS Word Search Acrobat Maintenance Acrobat Manifest Acrobat Menu Acrobat Merge Acrobat Open Acrobat PDFPage Acrobat Plugin Acrobat Preferences Acrobat Preflight Acrobat Print Acrobat Python Acrobat Reader Acrobat Reader Localized Acrobat Reference Acrobat Registered Products Acrobat SCA Acrobat SCA Updater Acrobat Sequ Acrobat Sign Acrobat Stamps Acrobat URL List Mac Acrobat URL List Windows Acrobat Watermark Acrobat Windows Acrobat Windows Reader Admin Admin Account Admin Apachectl Admin ConfigCode Admin configCode Admin Device Management Admin LaunchServices Admin Locationd Admin loginitem Admin Maintenance Admin Mobileconfig Admin NetWork Admin Permission Admin Pkg Admin Power Management Admin Printer Admin Printer Basic Admin Printer Custompapers Admin SetUp Admin SMB Admin softwareupdate Admin Support Admin System Information Admin TCC Admin Tools Admin Umask Admin Users Admin Volumes Admin XProtect Adobe Adobe AUSST Adobe Bridge Adobe Documents Adobe FDKO Adobe Fonts Adobe Reference Adobe RemoteUpdateManager Adobe Sap Code AppKit Apple AppleScript AppleScript Duplicate AppleScript entire contents AppleScript List AppleScript ObjC AppleScript Osax AppleScript PDF AppleScript Pictures AppleScript record AppleScript Video Applications AppStore Archive Archive Keka Attributes Automator BackUp Barcode Barcode Decode Barcode QR Bash Basic Basic Path Bluetooth BOX Browser Calendar CD/DVD Choose Chrome Chromedriver CIImage CityCode CloudStorage Color Color NSColor Color NSColorList com.apple.LaunchServices.OpenWith Console Contacts CotEditor CURL current application Date&Time delimiters Desktop Desktop Position Device Diff Disk do shell script Dock Dock Launchpad DropBox Droplet eMail Encode % Encode Decode Encode HTML Entity Encode UTF8 Error EXIFData exiftool ffmpeg File File Name Finder Finder Window Firefox Folder FolderAction Font List FontCollections Fonts Fonts Asset_Font Fonts ATS Fonts Emoji Fonts Maintenance Fonts Morisawa Fonts Python Fonts Variable Foxit GIF github Guide HTML Icon Icon Assets.car Illustrator Image Events ImageOptim Input Dictionary iPhone iWork Javascript Jedit Ω Json Label Language Link locationd lsappinfo m3u8 Mail Map Math Media Media AVAsset Media AVconvert Media AVFoundation Media AVURLAsset Media Movie Media Music Memo Messages Microsoft Microsoft Edge Microsoft Excel Microsoft Fonts Microsoft Office Microsoft Office Link Microsoft OneDrive Microsoft Teams Mouse Music Node Notes NSArray NSArray Sort NSAttributedString NSBezierPath NSBitmapImageRep NSBundle NSCFBoolean NSCharacterSet NSData NSDecimalNumber NSDictionary NSError NSEvent NSFileAttributes NSFileManager NSFileManager enumeratorAtURL NSFont NSFontManager NSGraphicsContext NSGraphicsContext Crop NSImage NSIndex NSKeyedArchiver NSKeyedUnarchiver NSLocale NSMetadataItem NSMutableArray NSMutableDictionary NSMutableString NSNotFound NSNumber NSOpenPanel NSPasteboard NSpoint NSPredicate NSRange NSRect NSRegularExpression NSRunningApplication NSScreen NSSet NSSize NSString NSString stringByApplyingTransform NSStringCompareOptions NSTask NSTimeZone NSUbiquitous NSURL NSURL File NSURLBookmark NSURLComponents NSURLResourceKey NSURLSession NSUserDefaults NSUUID NSView NSWorkspace Numbers OAuth PDF PDF Image2PDF PDF MakePDF PDF nUP PDF Pymupdf PDF Pypdf PDFContext PDFDisplayBox PDFImageRep PDFKit PDFKit Annotation PDFKit AnnotationWidget PDFKit DocumentPermissions PDFKit OCR PDFKit Outline PDFKit Start PDFPage PDFPage Rotation PDFView perl Photoshop PlistBuddy pluginkit plutil postalcode PostScript PowerShell prefPane Preview Python Python eyed3 Python pip QuickLook QuickTime ReadMe Regular Expression Reminders ReName Repeat RTF Safari SaveFile ScreenCapture ScreenSaver Script Editor Script Menu SF Symbols character id SF Symbols Entity Shortcuts Shortcuts Events sips Skype Slack Sound Spotlight sqlite StandardAdditions StationSearch Subtitles LRC Subtitles SRT Subtitles VTT Swift swiftDialog System Events System Settings 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 VMware Fusion Wacom Weather webarchive webp Wifi Windows XML XML EPUB XML HTML XML LSSharedFileList XML LSSharedFileList sfl2 XML LSSharedFileList sfl3 XML objectsForXQuery XML OPML XML Plist XML Plist System Events XML RSS XML savedSearch XML SVG XML TTML XML webloc XML xmllint XML XMP YouTube Zero Padding zoom