Zero Padding

[リネーム] ファイル名の中に含まれる連続した数字をゼロサプレスにしてリネーム

フォルダ選択_ファイル名数値ゼロサプレス.scpt

AppleScript サンプルコード

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

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003(* アプリケーションのインストール調査 v1
004ファイル名の数列をとにかくゼロ埋めして
005bashでファイル名順にならぶようにする
006
007フォルダを選択して
008フォルダの中のファイル名を一括返却します
009
010
011TEXT_F1_S2_E4.csv
012
013TEXT_F00001_S00002_E00004.csv
014のように
015ファイル名の中の連続する数字をゼロサプレスします。
016
017com.cocolog-nifty.quicktimer.icefloe  *)
018----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
019use AppleScript version "2.8"
020use framework "Foundation"
021use framework "UniformTypeIdentifiers"
022use framework "AppKit"
023use scripting additions
024property refMe : a reference to current application
025
026#############################
027#設定項目 リーディング0の桁数
028set strAddZeroNo to ("00000") as text
029
030#############################
031#ダイアログ
032set strName to (name of current application) as text
033if strName is "osascript" then
034  tell application "SystemUIServer" to activate
035else
036  tell current application to activate
037end if
038#デスクトップ
039set appFileManager to refMe's NSFileManager's defaultManager()
040set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSDesktopDirectory) inDomains:(refMe's NSUserDomainMask))
041set ocidDesktopDirPathURL to ocidURLsArray's firstObject()
042set aliasDesktopDirPath to (ocidDesktopDirPathURL's absoluteURL()) as alias
043set strMes to "フォルダを選んでください" as text
044set strPrompt to "フォルダを選択してください" as text
045try
046  tell application "SystemUIServer"
047    activate
048    set aliasResponse to (choose folder strMes with prompt strPrompt default location aliasDesktopDirPath with invisibles and showing package contents without multiple selections allowed) as alias
049  end tell
050on error
051  log "エラーしました"
052  return "エラーしました"
053end try
054
055#############################
056#コンテンツ収集
057set strDirPath to (POSIX path of aliasResponse) as text
058set ocidDirPathStr to refMe's NSString's stringWithString:(strDirPath)
059set ocidDirPath to ocidDirPathStr's stringByStandardizingPath()
060set ocidDirPathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidDirPath) isDirectory:true)
061#
062set ocidOption to (refMe's NSDirectoryEnumerationSkipsHiddenFiles)
063set ocidKeyArray to refMe's NSArray's arrayWithArray:({(refMe's NSURLPathKey), (refMe's NSURLIsDirectoryKey), (refMe's NSURLIsSymbolicLinkKey)})
064set listSubPathResult to (appFileManager's contentsOfDirectoryAtURL:(ocidDirPathURL) includingPropertiesForKeys:(ocidKeyArray) options:(ocidOption) |error| :(reference))
065set ocidSubPathURLArray to item 1 of listSubPathResult
066#一応ソートしてく
067set ocidDescriptor to refMe's NSSortDescriptor's sortDescriptorWithKey:("absoluteString") ascending:(yes) selector:("localizedStandardCompare:")
068set ocidDescriptorArray to refMe's NSArray's arrayWithObject:(ocidDescriptor)
069set ocidSubPathURLArray to ocidSubPathURLArray's sortedArrayUsingDescriptors:(ocidDescriptorArray)
070#############################
071#リネーム用の正規表現
072set ocidOption to (refMe's NSRegularExpressionAnchorsMatchLines)
073set listResponse to refMe's NSRegularExpression's regularExpressionWithPattern:("(€€d+)") options:(ocidOption) |error| :(reference)
074set appRegEx to (item 1 of listResponse)
075#置換用のゼロ テキストの初期化
076set ocidZeroString to refMe's NSMutableString's alloc()'s init()
077#コンテンツを順番に処理
078repeat with itemFileUrl in ocidSubPathURLArray
079  #コンテナディレクトリ
080  set ocidContainerDirPathURL to itemFileUrl's URLByDeletingLastPathComponent()
081  #ファイル名
082  set ocidFileName to itemFileUrl's lastPathComponent()
083  #コピーして
084  set ocidDistFileName to ocidFileName's mutableCopy()
085  #文字数数えて
086  set ocidLegth to ocidFileName's |length|()
087  #レンジにして
088  set ocidRange to refMe's NSRange's NSMakeRange(0, ocidLegth)
089  #正義表現で数値にマッチした範囲をリストにする
090  set ocidMachArray to (appRegEx's matchesInString:(ocidFileName) options:(0) range:(ocidRange))
091  #マッチした個数のカウント
092  set numCntArray to ocidMachArray's |count|()
093  #置換のリピートは後ろから
094  repeat with itemIntNo from (numCntArray - 1) to 0 by -1
095    #ゼロテキストを初期化
096    (ocidZeroString's setString:(strAddZeroNo))
097    #ゼロの文字数のレンジ
098    set numAddZero to ocidZeroString's |length|()
099    #マッチしたレコードを取り出して
100    set ocidItemMach to (ocidMachArray's objectAtIndex:(itemIntNo))
101    #レンジにする
102    set ocidMachRange to ocidItemMach's range()
103    #マッチしたレンジで文字列(数字)を取り出して
104    set ocidRangeString to (ocidFileName's substringWithRange:(ocidMachRange))
105    #ゼロテキストの追加する
106    (ocidZeroString's appendString:(ocidRangeString))
107    #ゼロと数字のレンジを数えて
108    set numTempLength to ocidZeroString's |length|()
109    #指定の桁数で後ろから取り出す
110    set ocidPddNo to (ocidZeroString's substringFromIndex:(numTempLength - numAddZero))
111    #コピーしておいたファイル名のレンジの文字をゼロパディングした文字に置換
112    set ocidDistFileName to (ocidDistFileName's stringByReplacingCharactersInRange:(ocidMachRange) withString:(ocidPddNo))
113  end repeat
114  #マッチした数だけ処理が終わればそれが新しいファイル名なので
115  #リネーム先のファイルURLを生成しておく
116  set ocidDistFilePathURL to (ocidContainerDirPathURL's URLByAppendingPathComponent:(ocidDistFileName) isDirectory:(false))
117  #リネーム用のファイルURLに移動=リネームする
118  set ListDone to (appFileManager's moveItemAtURL:(itemFileUrl) toURL:(ocidDistFilePathURL) |error| :(reference))
119  
120end repeat
121
122return
AppleScriptで生成しました

|

[Leading Zero]リーディングゼロ(ゼロサプレス)した日付テキストの取得(昔ながら)

リーディングゼロした日付.scpt

AppleScript サンプルコード

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

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002
003
004set dateNow to (current date)
005set numYear to (year of dateNow) as integer
006set numMonth to (month of dateNow) as integer
007set numDay to (day of dateNow) as integer
008
009log numYear
010log numMonth
011log numDay
012
013set strAddZero to ("00") as text
014set strYear to numYear as text
015set strMonth to (text -2 through -1 of (strAddZero & (numMonth as text))) as text
016set strDay to (text -2 through -1 of (strAddZero & (numDay as text))) as text
017
018log strYear
019log strMonth
020log strDay
021
022set strCurrentDate to (strYear & strMonth & strDay) as text
023log strCurrentDate
AppleScriptで生成しました

|

汎用ゼロパディング(桁数指定) Applescript

ゼロサプレス.scpt

AppleScript サンプルコード

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

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002#桁数
003set numLength to 4 as integer
004
005#マイナスにして
006set numThrough to (numLength * -1) as number
007#ゼロを追加するテキスト初期化
008set strZero to ("") as text
009##桁数分ゼロを追加
010repeat numLength times
011  set strZero to (strZero & "0") as text
012end repeat
013
014#本処理
015repeat with numCntNo from 1 to 1000 by 1
016  set strAddZero to (strZero & numCntNo) as text
017  set strZeroSuppNo to (text numThrough through -1 of strAddZero) as text
018  log strZeroSuppNo
019end repeat
AppleScriptで生成しました

少し応用
AppleScript サンプルコード

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

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002
003##最大番号
004set strMexNO to 9999 as integer
005##テキストにして
006set strCntNo to strMexNO as text
007##桁数を調べ
008set numLength to (length of strCntNo) as integer
009##桁数をマイナスの値にしておく
010set numThrough to (numLength * -1) as number
011#ゼロを追加するテキスト初期化
012set strZeroPadd to ("") as text
013##桁数分ゼロを追加
014repeat numLength times
015  set strZeroPadd to (strZeroPadd & "0") as text
016end repeat
017
018set numCntNo to 0 as integer
019repeat 100 times
020  ##数値をテキストにして
021  set strCntNo to numCntNo as text
022  ##桁数分の0のテキストに数値を追加
023  set strZeroPaddNo to (strZeroPadd & strCntNo) as text
024  ##必要な桁数分だけ取り出す
025  set strPrintPageNO to (text numThrough through -1 of strZeroPaddNo) as text
026  log strPrintPageNO
027  
028  
029  set numCntNo to numCntNo + 11 as integer
030end repeat
AppleScriptで生成しました

|

小数点以下 X桁での丸め


AppleScript サンプルコード

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

AppleScript サンプルソース(参考)
行番号ソース
001#!/usr/bin/env osascript
002----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
003#
004# com.cocolog-nifty.quicktimer.icefloe
005----+----1----+----2----+-----3----+----4----+----5----+----6----+----7
006##自分環境がos12なので2.8にしているだけです
007use AppleScript version "2.8"
008use framework "Foundation"
009use scripting additions
010
011property refMe : a reference to current application
012
013set numNumber to (29.970029830933) as number
014
015set ocidDecimalNumber to refMe's NSDecimalNumber's decimalNumberWithString:(numNumber as text)
016set appNumberFormatter to refMe's NSNumberFormatter's alloc()'s init()
017appNumberFormatter's setPositiveFormat:("#,##0.00")
018set ocidDecimalNumber to appNumberFormatter's stringFromNumber:(ocidDecimalNumber)
019
020log ocidDecimalNumber as text
021log ocidDecimalNumber's doubleValue() as number
022-->(*29.97*)
AppleScriptで生成しました

|

汎用ゼロパディング(桁数指定)


サンプルコード

サンプルソース(参考)
行番号ソース
001
002log doAddLeadingZeros(1, 3)
003log doAddLeadingZeros(99, 3)
004log doAddLeadingZeros(100, 3)
005log doAddLeadingZeros(1, 4)
006log doAddLeadingZeros(99, 4)
007log doAddLeadingZeros(100, 4)
008log doAddLeadingZeros(1000, 4)
009
010
011
012
013on doAddLeadingZeros(argNo, argAddZeros)
014  #渡された数値
015  set numArgNo to argNo as integer
016  set strArgNo to argNo as text
017  #渡された桁数に10のべき乗
018  set numArgAddZeros to argAddZeros as integer
019  set numThresholdDigits to (10 ^ argAddZeros) as integer
020  #渡された数値が小さければ0を付与する処理をする
021  if numArgNo < numThresholdDigits then
022    #戻し値用のテキストを初期化
023    set strLeadingZeros to ("") as text
024    #渡された数値の桁数を数える
025    set numCntLength to (length of strArgNo) as integer
026    #追加する0の数
027    set numAddZero to (numArgAddZeros - numCntLength) as integer
028    #戻し値用のテキストに↑の数だけ0を追加
029    repeat numAddZero times
030      set strLeadingZeros to (strLeadingZeros & "0") as text
031    end repeat
032    #戻し値用の0に渡された値を並べてテキストで戻す
033    set strArgNo to (strLeadingZeros & strArgNo) as text
034    return strArgNo
035  else
036    #処理不要ならそのままテキストで戻す
037    return strArgNo as text
038  end if
039end doAddLeadingZeros
AppleScriptで生成しました

|

[NSNumberFormatter]数値→ゼロパディングされたテキスト


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

#!/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.5"
use framework "Foundation"
use scripting additions
property refMe : a reference to current application


set numNo to 1 as integer
set ocidFormatter to refMe's NSNumberFormatter's alloc()'s init()
ocidFormatter's setMinimumIntegerDigits:(3)
ocidFormatter's setMaximumIntegerDigits:(3)
set ocidDecStr to (ocidFormatter's stringFromNumber:(numNo))
log ocidDecStr as text
-->(*001*)

set numNo to 99 as integer
set ocidFormatter to refMe's NSNumberFormatter's alloc()'s init()
ocidFormatter's setMinimumIntegerDigits:(3)
ocidFormatter's setMaximumIntegerDigits:(3)
set ocidDecStr to (ocidFormatter's stringFromNumber:(numNo))
log ocidDecStr as text
-->(*099*)

set numNo to 120 as integer
set ocidFormatter to refMe's NSNumberFormatter's alloc()'s init()
ocidFormatter's setMinimumIntegerDigits:(3)
ocidFormatter's setMaximumIntegerDigits:(3)
set ocidDecStr to (ocidFormatter's stringFromNumber:(numNo))
log ocidDecStr as text
-->(*120*)


|

3桁ゼロパディング


サンプルコード

サンプルソース(参考)
行番号ソース
001set numCnt to 0 as number
002
003repeat 100 times
004  set numCnt to numCnt + 1 as number
005  set strZeroPadd to "000" as text
006  set strZeroPadd to (strZeroPadd & (numCnt as text)) as text
007  set strZeroPadd to (text -3 through -1 of strZeroPadd) as text
008  
009  log strZeroPadd
010end repeat
AppleScriptで生成しました

|

整数のゼロパディング

stringByPaddingToLengthからの
substringFromIndex

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

#!/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

##元になる整数
set numInteger to 10 as integer

####指定桁数
set numZeroSuppCnt to 6 as integer
####出力用テキスト初期化
set ocidZeroSupText to refMe's NSMutableString's stringWithCapacity:0
####0ゼロを指定桁数だけ並べたテキストを作る
set ocidZeroSupText to ocidZeroSupText's stringByPaddingToLength:numZeroSuppCnt withString:"0" startingAtIndex:0
####後ろに値をテキストで追加する
ocidZeroSupText's appendString:(numInteger as text)
####追加した数値の桁数
set nimIntLength to (numInteger as text)'s length as integer
####桁数分減らしたテキストを取り出す
set ocidZeroSupStr to ocidZeroSupText's substringFromIndex:nimIntLength
####戻り値
log ocidZeroSupStr as text



|

[AppleScript]小数点以下桁揃え(切り捨て)

set numMM to 3 as number

set numPt to numMM * 2.8346456693 as number
-->(*8.5039370079*)

set strPt to (numPt as text)
-->(*8.5039370079*)
set AppleScript's text item delimiters to "."
set listPt to every text item of strPt as list
set AppleScript's text item delimiters to ""
-->{8, 5039370079}
set strPtInt to text item 1 of listPt as text
-->(*8*)
set strPtDecimal to text item 2 of listPt as text
-->(*5039370079*)
set strPtDecimal to (text 1 through 2 of (strPtDecimal & "00")) as text
-->(*5*)
set numPt to ("" & strPtInt & "." & strPtDecimal & "") as number
-->(*8.5*)

|

[Padding]ゼロパディング(日時)

日付




set strCommandText to ("/bin/date +%Y%m%d") as text
set strDate to (do shell script strCommandText) as text
-->"20220401"



###年を取り出して
set numYear to (year of (current date)) as number
###テキストにして
set strYear to numYear as text


###月を取り出して
set numMonth to (month of (current date)) as number
###テキストにして
set strMonth to numMonth as text
###数値に00を足して最大4桁にして後ろの2桁取る
set strMonth to (text -2 through -1 of ("00" & strMonth)) as text


###日を取り出して
set strDays to (day of (current date)) as text
###数値に00を足して最大4桁にして後ろの2桁取る
set strDays to (text -2 through -1 of ("00" & strDays)) as text

###順番に並べる
set strDate to (strYear & strMonth & strDays) as text



時間
set strCommandText to ("/bin/date +%H%M%S") as text
set strDate to (do shell script strCommandText) as text
-->"090008"



###時間を取り出して
set numTime to (time of (current date)) as integer
###時だけ取り出し
set theHours to numTime div hours
###数値に00を足して最大4桁にして後ろの2桁取る
set theHours to (text -2 through -1 of ("00" & theHours)) as text
###分だけ取り出し
set theMinutes to (numTime - (theHours) * hours) div minutes
###数値に00を足して最大4桁にして後ろの2桁取る
set theMinutes to (text -2 through -1 of ("00" & theMinutes)) as text
###秒取り出して
set theSeconds to numTime mod minutes
###数値に00を足して最大4桁にして後ろの2桁取る
set theSeconds to (text -2 through -1 of ("00" & theSeconds)) as text
###順番に並べる
set theTime to (theHours & theMinutes & theSeconds) as text

|

その他のカテゴリー

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