Any way to make Applescript count "&" as a word? - applescript

When I tell Applescript to count the words of a string like "A & B" with the text item delimiters set to space, it returns 2. It is not counting the ampersand as a word. Is there any way to change that? After all, "&" means "and", which does count as a word.

Here's a workaround:
set theString to "A & B"
set wordCount to do shell script "wc -w <<< " & quoted form of theString & " | tr -d ' '"
In this example, it returns: 3

This script uses the Satimage.osax scripting addition. After putting the Satimage.osax file in your folder /Library/ScriptingAdditions/Satimage.osax, you should be able to view its dictionary and all of its commands in ScriptEditor.app by going to menu item “Window/Library”
Download Satimage Scripting Addition
set theString to "A & B"
set toExclude to {" "} as list -- Variable For Items To Be Removed From Your List In Line 4
set theWordCount to items of theString -- Returns The Items Of Your String As A List {"A", " ", "&", " ", "B"}
set resultList to exclude items toExclude from theWordCount -- Removes Specified Items From The List
set theWordCount to count items of resultList -- Returns 3 As Your Count
get theWordCount -- This Line Is Not Necessary And Can Be Removed

Related

How to log actual value without introducing a variable in AppleScript [duplicate]

I am just trying to log the state of objects throughout the life of my applescript. In other languages, object's toString() methods will render the text equivalent and I can use those. In AppleScript, this does not seem to be the case.
convert applescript object to string (similar to toString)
Will output the finder object (and its properties) to the "Results" window of AppleScript Editor, but only if it is the last statement which gets executed.
If I have a trace() statement (which takes a message for logging purposes):
on trace(message)
do shell script "cat >>~/log/applescript.txt <<END_OF_THE_LOG
" & (message as text) & "
END_OF_THE_LOG"
end trace
and try to log the same object, I get
Can’t make properties of application "Finder" into type text.
I'm open to better ways of logging to a console, but would like to find out how to write an object's properties (like AppleScript Editor does) in the middle of a script for testing either way.
AppleScript doesn't make it easy:
log only logs while running in AppleScript Editor or when running via osascript (to stderr in that case) - the output will be lost in other cases, such as when applications run a script with the NSAppleScript Cocoa class.
log only accepts one argument; while it does accept any object type, it doesn't make it easy to get a meaningful representation of non-built-in types: try log me to get information about the script itself, for instance; frequently, log (get properties of <someObj>) must be used to get meaningful information; note the cumbersome syntax, which is required, because just using log properties of <someObj> typically merely prints the name of the reference form instead of the properties it points to (e.g, log properties of me uselessly outputs just (*properties*)).
In general, AppleScript makes it very hard to get meaningful text representations of objects of non-built-in types: <someObj> as text (same as: <someObj> as string) annoyingly breaks - throws a runtime error - for such objects; try me as text.
Below are helper subroutines that address these issues:
dlog() is a subroutine that combines deriving meaningful text representations of any objects with the ability to write to multiple log targets (including syslog and files) based on a global config variable.
toString() (effectively embedded in dlog()) is a subroutine that takes a single object of any type and derives a meaningful text representation from it.
Tip of the hat to #1.61803; his answer provided pointers for implementing the various logging targets.
Examples:
# Setup: Log to syslog and a file in the home dir.
# Other targets supported: "log", "alert"
# Set to {} to suppress logging.
set DLOG_TARGETS to { "syslog", "~/as.log" }
# Log properties of the front window of frontmost application.
dlog(front window of application (path to frontmost application as text))
# Log properties of own front window; note the *list* syntax for multiple args.
dlog({"my front window: ", front window})
# Get properties of the running script as string.
toString(me) # ->, e.g.: [script name="sandbox"] {selection:insertion point after character 2475 of text of document "sandbox2.scpt", frontmost:true, class:application, name:"AppleScript Editor", version:"2.6"}
See the source-code comments above each subroutine for details.
dlog() source code
# Logs a text representation of the specified object or objects, which may be of any type, typically for debugging.
# Works hard to find a meaningful text representation of each object.
# SYNOPSIS
# dlog(anyObjOrListOfObjects)
# USE EXAMPLES
# dlog("before") # single object
# dlog({ "front window: ", front window }) # list of objects
# SETUP
# At the top of your script, define global variable DLOG_TARGETS and set it to a *list* of targets (even if you only have 1 target).
# set DLOG_TARGETS to {} # must be a list with any combination of: "log", "syslog", "alert", <posixFilePath>
# An *empty* list means that logging should be *disabled*.
# If you specify a POSIX file path, the file will be *appended* to; variable references in the path
# are allowed, and as a courtesy the path may start with "~" to refer to your home dir.
# Caveat: while you can *remove* the variable definition to disable logging, you'll take an additional performance hit.
# SETUP EXAMPLES
# For instance, to use both AppleScript's log command *and* display a GUI alert, use:
# set DLOG_TARGETS to { "log", "alert" }
# Note:
# - Since the subroutine is still called even when DLOG_TARGETS is an empty list,
# you pay a performancy penalty for leaving dlog() calls in your code.
# - Unlike with the built-in log() method, you MUST use parentheses around the parameter.
# - To specify more than one object, pass a *list*. Note that while you could try to synthesize a single
# output string by concatenation yourself, you'd lose the benefit of this subroutine's ability to derive
# readable text representations even of objects that can't simply be converted with `as text`.
on dlog(anyObjOrListOfObjects)
global DLOG_TARGETS
try
if length of DLOG_TARGETS is 0 then return
on error
return
end try
# The following tries hard to derive a readable representation from the input object(s).
if class of anyObjOrListOfObjects is not list then set anyObjOrListOfObjects to {anyObjOrListOfObjects}
local lst, i, txt, errMsg, orgTids, oName, oId, prefix, logTarget, txtCombined, prefixTime, prefixDateTime
set lst to {}
repeat with anyObj in anyObjOrListOfObjects
set txt to ""
repeat with i from 1 to 2
try
if i is 1 then
if class of anyObj is list then
set {orgTids, AppleScript's text item delimiters} to {AppleScript's text item delimiters, {", "}} # '
set txt to ("{" & anyObj as string) & "}"
set AppleScript's text item delimiters to orgTids # '
else
set txt to anyObj as string
end if
else
set txt to properties of anyObj as string
end if
on error errMsg
# Trick for records and record-*like* objects:
# We exploit the fact that the error message contains the desired string representation of the record, so we extract it from there. This (still) works as of AS 2.3 (OS X 10.9).
try
set txt to do shell script "egrep -o '\\{.*\\}' <<< " & quoted form of errMsg
end try
end try
if txt is not "" then exit repeat
end repeat
set prefix to ""
if class of anyObj is not in {text, integer, real, boolean, date, list, record} and anyObj is not missing value then
set prefix to "[" & class of anyObj
set oName to ""
set oId to ""
try
set oName to name of anyObj
if oName is not missing value then set prefix to prefix & " name=\"" & oName & "\""
end try
try
set oId to id of anyObj
if oId is not missing value then set prefix to prefix & " id=" & oId
end try
set prefix to prefix & "] "
set txt to prefix & txt
end if
set lst to lst & txt
end repeat
set {orgTids, AppleScript's text item delimiters} to {AppleScript's text item delimiters, {" "}} # '
set txtCombined to lst as string
set prefixTime to "[" & time string of (current date) & "] "
set prefixDateTime to "[" & short date string of (current date) & " " & text 2 thru -1 of prefixTime
set AppleScript's text item delimiters to orgTids # '
# Log the result to every target specified.
repeat with logTarget in DLOG_TARGETS
if contents of logTarget is "log" then
log prefixTime & txtCombined
else if contents of logTarget is "alert" then
display alert prefixTime & txtCombined
else if contents of logTarget is "syslog" then
do shell script "logger -t " & quoted form of ("AS: " & (name of me)) & " " & quoted form of txtCombined
else # assumed to be a POSIX file path to *append* to.
set fpath to contents of logTarget
if fpath starts with "~/" then set fpath to "$HOME/" & text 3 thru -1 of fpath
do shell script "printf '%s\\n' " & quoted form of (prefixDateTime & txtCombined) & " >> \"" & fpath & "\""
end if
end repeat
end dlog
toString() source code
# Converts the specified object - which may be of any type - into a string representation for logging/debugging.
# Tries hard to find a readable representation - sadly, simple conversion with `as text` mostly doesn't work with non-primitive types.
# An attempt is made to list the properties of non-primitive types (does not always work), and the result is prefixed with the type (class) name
# and, if present, the object's name and ID.
# EXAMPLE
# toString(path to desktop) # -> "[alias] Macintosh HD:Users:mklement:Desktop:"
# To test this subroutine and see the various representations, use the following:
# repeat with elem in {42, 3.14, "two", true, (current date), {"one", "two", "three"}, {one:1, two:"deux", three:false}, missing value, me, path to desktop, front window of application (path to frontmost application as text)}
# log my toString(contents of elem)
# end repeat
on toString(anyObj)
local i, txt, errMsg, orgTids, oName, oId, prefix
set txt to ""
repeat with i from 1 to 2
try
if i is 1 then
if class of anyObj is list then
set {orgTids, AppleScript's text item delimiters} to {AppleScript's text item delimiters, {", "}}
set txt to ("{" & anyObj as string) & "}"
set AppleScript's text item delimiters to orgTids # '
else
set txt to anyObj as string
end if
else
set txt to properties of anyObj as string
end if
on error errMsg
# Trick for records and record-*like* objects:
# We exploit the fact that the error message contains the desired string representation of the record, so we extract it from there. This (still) works as of AS 2.3 (OS X 10.9).
try
set txt to do shell script "egrep -o '\\{.*\\}' <<< " & quoted form of errMsg
end try
end try
if txt is not "" then exit repeat
end repeat
set prefix to ""
if class of anyObj is not in {text, integer, real, boolean, date, list, record} and anyObj is not missing value then
set prefix to "[" & class of anyObj
set oName to ""
set oId to ""
try
set oName to name of anyObj
if oName is not missing value then set prefix to prefix & " name=\"" & oName & "\""
end try
try
set oId to id of anyObj
if oId is not missing value then set prefix to prefix & " id=" & oId
end try
set prefix to prefix & "] "
end if
return prefix & txt
end toString
Just use the log statement in AppleScript Editor. When you view the results in Applescript Editor, at the bottom of the window press the "Events" button. Normally the "Results" button is pressed and then you only see the result of the last statement as you mention. So change the button to "Events". This will show you everything that is happening as the script runs, and additionally all of the log statements that you put throughout the code too. Note that the log statements do not have to be text. You can log any object.
This is the best way to debug your script and see what is happening. As an example try this and look at the "Events". Realistically thought you don't need a lot of log statements if you view the Events because everything is already logged!
set someFolder to path to desktop
log someFolder
tell application "Finder"
set someItem to first item of someFolder
log someItem
set itemProps to properties of someItem
log itemProps
end tell
Try any of the following:
# echo to file
do shell script "echo " & quoted form of (myObj as string) & ¬
" > ~/Desktop/as_debug.txt"
# write to file
set myFile to open for access (path to desktop as text) & ¬
"as_debug2.txt" with write permission
write myObj to myFile
close access myFile
# log to syslog
do shell script "logger -t 'AS DEBUG' " & myObj
# show dialog
display dialog "ERROR: " & myObj
If what you're trying to log is not text, you might try:
quoted form of (myObj as string)
Here are examples of console log:
set my_int to 9945
log my_int
set my_srt to "Hamza"
log my_srt
set my_array ["Apple","Mango","Banana","Gava"]
log my_array
set my_obj to {"Ali"} as string
log my_obj
do shell script "echo '" & (current date) & ": Found " & Thisfilename & "' >> ~/logs/MyGreatAppleScript.log"
Similar to toString()...
on TextOf(aVariable)
try
return "" & aVariable
on error errm
if errm begins with "Can’t make " ¬
and errm ends with " into type Unicode text." then ¬
return text 12 through -25 of errm
return "item of class " & (class of aVariable) & return & errm
end try
end TextOf
Easiest way to know your values-
display dialog "my variable: " & myVariableName
For scripts that run long and I’m not looking at the screen, I like to have applescript say out loud what it’s doing.
Ie.
say “This is a log statement.”
If inside a tell statement:
tell me to say “This is a log statement.”

Applescript: Split sentence at cursor - remove punctuation from selection, capitalize letter and insert period

I'm new to AppleScript, but think it can automate a minor annoyance I sometimes deal with.
Lets say I write: "I like pizza, put bacon on it!"
But I decide I want to split that into two sentences: "I like pizza. Put bacon in it!"
I'd like to be able to select the string ", p"
And with a keyboard shortcut, have a script remove any punctuation, add a period, and capitalize the first letter.
I figured out how to set System Preferences > Keyboard to run an automator service, running an AppleScript, but I can't google enough info to create the script from scratch.
Any help or direction would be great!
Alternative: Since Automator supports other interpreters too, there is no strict need to use AppleScript.
Here's an alternative solution that uses a Run Shell Script action to combine bash with awk, which makes for much less code:
Create an Automator service that:
receives selected text in any application
has check box Output replaces selected text checked
contains a Run Shell Script action with the code below
and then invoke the service with the entire sentence ("I like pizza, put bacon on it!") selected.
awk -F ', ' '{
printf $1 # print the first "field"; lines without ", " only have 1 field
for (i=2; i<=NF; ++i) { # all other fields, i.e., all ", "-separated clauses.
# Join the remaining clauses with ". " with their 1st char. capitalized.
printf ". " toupper(substr($i,1,1)) substr($i,2)
}
printf "\n" # terminate the output with a newline
}'
Caveat: incredibly, awk (as of OS X 10.9.2) doesn't process foreign characters correctly - passing them through unmodified works, but toupper() and tolower() do not recognize them as letters. Thus, this solution will not correctly work for input where a foreign char. must be uppercased; e.g.: "I like pizza, ṕut bacon on it!" will NOT convert the ṕ to Ṕ.
If you:
create an Automator service that:
receives selected text in any application
has check box Output replaces selected text checked
contains a Run AppleScript action with the code below
and then invoke the service with the entire sentence ("I like pizza, put bacon on it!") selected
it should do what you want.
on run {input, parameters}
# Initialize return variable.
set res to ""
# Split the selection into clauses by ", ".
set {orgTIDs, AppleScript's text item delimiters} to {AppleScript's text item delimiters, {", "}} #'
set clauses to text items of item 1 of input
set AppleScript's text item delimiters to orgTIDs #'
# Join the clauses with ". ", capitalizing the first letter of all clauses but the first.
repeat with clause in clauses
if res = "" then
set res to clause
else
set res to res & ". " & my capitalizeFirstChar(clause)
end if
end repeat
# Return the result
return res
end run
# Returns the specified string with its first character capitalized.
on capitalizeFirstChar(s)
set {orgTIDs, AppleScript's text item delimiters} to {AppleScript's text item delimiters, {""}} #'
set res to my toUpper((text item 1 of s) as text) & text items 2 thru -1 of s as text
set AppleScript's text item delimiters to orgTIDs #'
return res
end capitalizeFirstChar
# Converts the specified string (as a whole) to uppercase.
on toUpper(s)
tell AppleScript to return do shell script "export LANG='" & user locale of (system info) & ".UTF-8'; tr [:lower:] [:upper:] <<< " & quoted form of s
end toUpper

Can a whose clause be used to filter text element lists such as words, characters and paragraphs

I have the following working example AppleScript snippet:
set str to "This is a string"
set outlist to {}
repeat with wrd in words of str
if wrd contains "is" then set end of outlist to wrd
end repeat
I know the whose clause in AppleScript can often be used to replace repeat loops such as this to significant performance gain. However in the case of text element lists such as words, characters and paragraphs I haven't been able to figure out a way to make this work.
I have tried:
set outlist to words of str whose text contains "is"
This fails with:
error "Can’t get {\"This\", \"is\", \"a\", \"string\"} whose text contains \"is\"." number -1728
, presumably because "text" is not a property of the text class. Looking at the AppleScript Reference for the text class, I see that "quoted form" is a property of the text class, so I half expected this to work:
set outlist to words of str whose quoted form contains "is"
But this also fails, with:
error "Can’t get {\"This\", \"is\", \"a\", \"string\"} whose quoted form contains \"is\"." number -1728
Is there any way to replace such a repeat loop with a whose clause in AppleScript?
From page 534 (working with text) of AppleScript 1-2-3
AppleScript does not consider paragraphs, words, and characters to be
scriptable objects that can be located by using the values of their
properties or elements in searches using a filter reference, or whose
clause.
Here is another approach:
set str to "This is a string"
set outlist to paragraphs of (do shell script "grep -o '\\w*is\\w*' <<< " & quoted form of str)
As #adayzdone has shown. It looks like you are out of luck with that.
But you could try using the offset command like this.
set wrd to "I am here"
set outlist to {}
set str to " This is a word"
if ((offset of space & "is" & space in str) as integer) is greater than 0 then set end of outlist to wrd
Note the spaces around "is" . This makes sure Offset is finding a whole word. Offset will find the first matching "is" in "This" otherwise.
UPDATE.
To use it as the OP wants
set wrd to "I am here"
set outlist to {}
set str to " This is a word"
repeat with wrd in words of str
if ((offset of "is" in wrd) as integer) is greater than 0 then set end of outlist to (wrd as string)
end repeat
-->{"This", "is"}

How to log objects to a console with AppleScript

I am just trying to log the state of objects throughout the life of my applescript. In other languages, object's toString() methods will render the text equivalent and I can use those. In AppleScript, this does not seem to be the case.
convert applescript object to string (similar to toString)
Will output the finder object (and its properties) to the "Results" window of AppleScript Editor, but only if it is the last statement which gets executed.
If I have a trace() statement (which takes a message for logging purposes):
on trace(message)
do shell script "cat >>~/log/applescript.txt <<END_OF_THE_LOG
" & (message as text) & "
END_OF_THE_LOG"
end trace
and try to log the same object, I get
Can’t make properties of application "Finder" into type text.
I'm open to better ways of logging to a console, but would like to find out how to write an object's properties (like AppleScript Editor does) in the middle of a script for testing either way.
AppleScript doesn't make it easy:
log only logs while running in AppleScript Editor or when running via osascript (to stderr in that case) - the output will be lost in other cases, such as when applications run a script with the NSAppleScript Cocoa class.
log only accepts one argument; while it does accept any object type, it doesn't make it easy to get a meaningful representation of non-built-in types: try log me to get information about the script itself, for instance; frequently, log (get properties of <someObj>) must be used to get meaningful information; note the cumbersome syntax, which is required, because just using log properties of <someObj> typically merely prints the name of the reference form instead of the properties it points to (e.g, log properties of me uselessly outputs just (*properties*)).
In general, AppleScript makes it very hard to get meaningful text representations of objects of non-built-in types: <someObj> as text (same as: <someObj> as string) annoyingly breaks - throws a runtime error - for such objects; try me as text.
Below are helper subroutines that address these issues:
dlog() is a subroutine that combines deriving meaningful text representations of any objects with the ability to write to multiple log targets (including syslog and files) based on a global config variable.
toString() (effectively embedded in dlog()) is a subroutine that takes a single object of any type and derives a meaningful text representation from it.
Tip of the hat to #1.61803; his answer provided pointers for implementing the various logging targets.
Examples:
# Setup: Log to syslog and a file in the home dir.
# Other targets supported: "log", "alert"
# Set to {} to suppress logging.
set DLOG_TARGETS to { "syslog", "~/as.log" }
# Log properties of the front window of frontmost application.
dlog(front window of application (path to frontmost application as text))
# Log properties of own front window; note the *list* syntax for multiple args.
dlog({"my front window: ", front window})
# Get properties of the running script as string.
toString(me) # ->, e.g.: [script name="sandbox"] {selection:insertion point after character 2475 of text of document "sandbox2.scpt", frontmost:true, class:application, name:"AppleScript Editor", version:"2.6"}
See the source-code comments above each subroutine for details.
dlog() source code
# Logs a text representation of the specified object or objects, which may be of any type, typically for debugging.
# Works hard to find a meaningful text representation of each object.
# SYNOPSIS
# dlog(anyObjOrListOfObjects)
# USE EXAMPLES
# dlog("before") # single object
# dlog({ "front window: ", front window }) # list of objects
# SETUP
# At the top of your script, define global variable DLOG_TARGETS and set it to a *list* of targets (even if you only have 1 target).
# set DLOG_TARGETS to {} # must be a list with any combination of: "log", "syslog", "alert", <posixFilePath>
# An *empty* list means that logging should be *disabled*.
# If you specify a POSIX file path, the file will be *appended* to; variable references in the path
# are allowed, and as a courtesy the path may start with "~" to refer to your home dir.
# Caveat: while you can *remove* the variable definition to disable logging, you'll take an additional performance hit.
# SETUP EXAMPLES
# For instance, to use both AppleScript's log command *and* display a GUI alert, use:
# set DLOG_TARGETS to { "log", "alert" }
# Note:
# - Since the subroutine is still called even when DLOG_TARGETS is an empty list,
# you pay a performancy penalty for leaving dlog() calls in your code.
# - Unlike with the built-in log() method, you MUST use parentheses around the parameter.
# - To specify more than one object, pass a *list*. Note that while you could try to synthesize a single
# output string by concatenation yourself, you'd lose the benefit of this subroutine's ability to derive
# readable text representations even of objects that can't simply be converted with `as text`.
on dlog(anyObjOrListOfObjects)
global DLOG_TARGETS
try
if length of DLOG_TARGETS is 0 then return
on error
return
end try
# The following tries hard to derive a readable representation from the input object(s).
if class of anyObjOrListOfObjects is not list then set anyObjOrListOfObjects to {anyObjOrListOfObjects}
local lst, i, txt, errMsg, orgTids, oName, oId, prefix, logTarget, txtCombined, prefixTime, prefixDateTime
set lst to {}
repeat with anyObj in anyObjOrListOfObjects
set txt to ""
repeat with i from 1 to 2
try
if i is 1 then
if class of anyObj is list then
set {orgTids, AppleScript's text item delimiters} to {AppleScript's text item delimiters, {", "}} # '
set txt to ("{" & anyObj as string) & "}"
set AppleScript's text item delimiters to orgTids # '
else
set txt to anyObj as string
end if
else
set txt to properties of anyObj as string
end if
on error errMsg
# Trick for records and record-*like* objects:
# We exploit the fact that the error message contains the desired string representation of the record, so we extract it from there. This (still) works as of AS 2.3 (OS X 10.9).
try
set txt to do shell script "egrep -o '\\{.*\\}' <<< " & quoted form of errMsg
end try
end try
if txt is not "" then exit repeat
end repeat
set prefix to ""
if class of anyObj is not in {text, integer, real, boolean, date, list, record} and anyObj is not missing value then
set prefix to "[" & class of anyObj
set oName to ""
set oId to ""
try
set oName to name of anyObj
if oName is not missing value then set prefix to prefix & " name=\"" & oName & "\""
end try
try
set oId to id of anyObj
if oId is not missing value then set prefix to prefix & " id=" & oId
end try
set prefix to prefix & "] "
set txt to prefix & txt
end if
set lst to lst & txt
end repeat
set {orgTids, AppleScript's text item delimiters} to {AppleScript's text item delimiters, {" "}} # '
set txtCombined to lst as string
set prefixTime to "[" & time string of (current date) & "] "
set prefixDateTime to "[" & short date string of (current date) & " " & text 2 thru -1 of prefixTime
set AppleScript's text item delimiters to orgTids # '
# Log the result to every target specified.
repeat with logTarget in DLOG_TARGETS
if contents of logTarget is "log" then
log prefixTime & txtCombined
else if contents of logTarget is "alert" then
display alert prefixTime & txtCombined
else if contents of logTarget is "syslog" then
do shell script "logger -t " & quoted form of ("AS: " & (name of me)) & " " & quoted form of txtCombined
else # assumed to be a POSIX file path to *append* to.
set fpath to contents of logTarget
if fpath starts with "~/" then set fpath to "$HOME/" & text 3 thru -1 of fpath
do shell script "printf '%s\\n' " & quoted form of (prefixDateTime & txtCombined) & " >> \"" & fpath & "\""
end if
end repeat
end dlog
toString() source code
# Converts the specified object - which may be of any type - into a string representation for logging/debugging.
# Tries hard to find a readable representation - sadly, simple conversion with `as text` mostly doesn't work with non-primitive types.
# An attempt is made to list the properties of non-primitive types (does not always work), and the result is prefixed with the type (class) name
# and, if present, the object's name and ID.
# EXAMPLE
# toString(path to desktop) # -> "[alias] Macintosh HD:Users:mklement:Desktop:"
# To test this subroutine and see the various representations, use the following:
# repeat with elem in {42, 3.14, "two", true, (current date), {"one", "two", "three"}, {one:1, two:"deux", three:false}, missing value, me, path to desktop, front window of application (path to frontmost application as text)}
# log my toString(contents of elem)
# end repeat
on toString(anyObj)
local i, txt, errMsg, orgTids, oName, oId, prefix
set txt to ""
repeat with i from 1 to 2
try
if i is 1 then
if class of anyObj is list then
set {orgTids, AppleScript's text item delimiters} to {AppleScript's text item delimiters, {", "}}
set txt to ("{" & anyObj as string) & "}"
set AppleScript's text item delimiters to orgTids # '
else
set txt to anyObj as string
end if
else
set txt to properties of anyObj as string
end if
on error errMsg
# Trick for records and record-*like* objects:
# We exploit the fact that the error message contains the desired string representation of the record, so we extract it from there. This (still) works as of AS 2.3 (OS X 10.9).
try
set txt to do shell script "egrep -o '\\{.*\\}' <<< " & quoted form of errMsg
end try
end try
if txt is not "" then exit repeat
end repeat
set prefix to ""
if class of anyObj is not in {text, integer, real, boolean, date, list, record} and anyObj is not missing value then
set prefix to "[" & class of anyObj
set oName to ""
set oId to ""
try
set oName to name of anyObj
if oName is not missing value then set prefix to prefix & " name=\"" & oName & "\""
end try
try
set oId to id of anyObj
if oId is not missing value then set prefix to prefix & " id=" & oId
end try
set prefix to prefix & "] "
end if
return prefix & txt
end toString
Just use the log statement in AppleScript Editor. When you view the results in Applescript Editor, at the bottom of the window press the "Events" button. Normally the "Results" button is pressed and then you only see the result of the last statement as you mention. So change the button to "Events". This will show you everything that is happening as the script runs, and additionally all of the log statements that you put throughout the code too. Note that the log statements do not have to be text. You can log any object.
This is the best way to debug your script and see what is happening. As an example try this and look at the "Events". Realistically thought you don't need a lot of log statements if you view the Events because everything is already logged!
set someFolder to path to desktop
log someFolder
tell application "Finder"
set someItem to first item of someFolder
log someItem
set itemProps to properties of someItem
log itemProps
end tell
Try any of the following:
# echo to file
do shell script "echo " & quoted form of (myObj as string) & ¬
" > ~/Desktop/as_debug.txt"
# write to file
set myFile to open for access (path to desktop as text) & ¬
"as_debug2.txt" with write permission
write myObj to myFile
close access myFile
# log to syslog
do shell script "logger -t 'AS DEBUG' " & myObj
# show dialog
display dialog "ERROR: " & myObj
If what you're trying to log is not text, you might try:
quoted form of (myObj as string)
Here are examples of console log:
set my_int to 9945
log my_int
set my_srt to "Hamza"
log my_srt
set my_array ["Apple","Mango","Banana","Gava"]
log my_array
set my_obj to {"Ali"} as string
log my_obj
do shell script "echo '" & (current date) & ": Found " & Thisfilename & "' >> ~/logs/MyGreatAppleScript.log"
Similar to toString()...
on TextOf(aVariable)
try
return "" & aVariable
on error errm
if errm begins with "Can’t make " ¬
and errm ends with " into type Unicode text." then ¬
return text 12 through -25 of errm
return "item of class " & (class of aVariable) & return & errm
end try
end TextOf
Easiest way to know your values-
display dialog "my variable: " & myVariableName
For scripts that run long and I’m not looking at the screen, I like to have applescript say out loud what it’s doing.
Ie.
say “This is a log statement.”
If inside a tell statement:
tell me to say “This is a log statement.”

Applescript repetitive renaming

I'm trying to make an AppleScript droplet to rename a bunch of images annoyingly formatted, but I found out my AppleScript skills have become nonexistent and I'm getting nowhere. So if possible, full code, not just snippets.
The file setup is always the same, but there are many variations (ex: Yellowst.Nat.Park.D12P55.DMS.3248.jpg)
It starts with a place name, should be a find and replace for a bunch of different strings, ("Yellowst.Nat.Park" -> "Yellowstone National Park")
Then it is followed by two numbers that should be changed in format (D12P55 -> [12x55]). They're always set up in a "D" followed by two numbers, a "P" and again two numbers.
And it ends with a random string, can be numbers, letters etc, which all have to go. They differ in format and length, no pattern in them.
Basically I want to go from "Yellowst.Nat.Park.D12P55.DMS.3248.jpg" to "Yellowstone National Park [02x03] .jpg" I want to add text afterwards so want to end with a space.
The best way to do this seems to me a repetitive find and replace for the first part, Make a list for a bunch of terms wich have to be replaced by a bunch of respective terms. Followed by a detection of the number format and ending with deleting of the random string after it.
Here is another approach.
property pictureFolder : (alias "Mac OS X:Users:Sam:Pictures:test:")
property findList : {"Yellowst.Nat.Park", "Jellyst.Nat.Park"}
property replaceList : {"Yellowstone National Park", "Jellystone \\& National Park"}
tell application "System Events"
set nameList to (name of every file of pictureFolder whose visible = true)
repeat with i from 1 to count of (list folder pictureFolder without invisibles)
set fileName to item i of nameList
set fileExtension to (name extension of (file fileName of pictureFolder))
repeat with j from 1 to count of findList
if fileName contains item j of findList then
set tempName to do shell script "echo " & fileName & " | sed 's/.D\\([0-9][0-9]\\)P\\([0-9][0-9]\\).*/[\\1x\\2] " & i & "." & fileExtension & "/'"
set tempName to do shell script "echo " & tempName & " | sed 's/^" & item j of findList & "/" & item j of replaceList & " /'"
set name of (file fileName of pictureFolder) to tempName
exit repeat
else if j = (count of findList) then
set tempName to do shell script "echo " & fileName & " | sed 's/[.]/ /g'"
set tempName to do shell script "echo " & tempName & " | sed 's/.D\\([0-9][0-9]\\)P\\([0-9][0-9]\\).*/ [\\1x\\2] " & i & "." & fileExtension & "/'"
set name of (file fileName of pictureFolder) to tempName
end if
end repeat
end repeat
end tell
To avoid duplicate names, I added a counter to the end of the file name. If there are no duplicates, you can use this instead:
set tempName to do shell script "echo " & fileName & " | sed 's/.D\\([0-9][0-9]\\)P\\([0-9][0-9]\\).*/[\\1x\\2] " & "." & fileExtension & "/'"
I like small challenges like this Sam. They're fun to me... maybe I'm sick ;). Anyway, I wrote you a handler to clean the file name as you requested. It's not really hard to manipulate text in applescript if you're comfortable with text item delimiters and such. These small challenges keep my text skills sharp.
NOTE: in the nameList property the name must end with a period or whatever character is just before the letter D in the number sequence DxxPxx as you mentioned.
So give this a try. Plug in a variety of fileNames and ensure it works how you want. Of course you need to put more values into the nameList and nameReplaceList properties too.
property nameList : {"Yellowst.Nat.Park."}
property nameReplaceList : {"Yellowstone National Park"}
set fileName to "Yellowst.Nat.Park.D12P55.DMS.3248.jpg"
cleanFilename(fileName)
(*================ SUBROUTINES ================*)
on cleanFilename(fileName)
-- first find the base name and file extension of the file name
set tids to AppleScript's text item delimiters
set ext to ""
if fileName contains "." then
set AppleScript's text item delimiters to "."
set textItems to text items of fileName
set ext to "." & item -1 of textItems
set baseName to (items 1 thru -2 of textItems) as text
set text item delimiters to ""
else
set baseName to fileName
end if
-- next find the pattern D, 2 numbers, P, and 2 numbers in the baseName
set chars to characters of baseName
set theSequence to missing value
repeat with i from 1 to (count of chars) - 6
set thisChar to item i of chars
if thisChar is "d" and item (i + 3) of baseName is "p" then
try
set firstNum to text (i + 1) thru (i + 2) of baseName
firstNum as number
set secondNum to text (i + 4) thru (i + 5) of baseName
secondNum as number
set theSequence to text i through (i + 5) of baseName
exit repeat
end try
end if
end repeat
-- now make the changes
if theSequence is not missing value then
set AppleScript's text item delimiters to theSequence
set theParts to text items of baseName
set fixedFirstPart to item 1 of theParts
repeat with i from 1 to count of nameList
if item i of nameList is fixedFirstPart then
set fixedFirstPart to item i of nameReplaceList
exit repeat
end if
end repeat
set fixedName to fixedFirstPart & " [" & firstNum & "x" & secondNum & "]" & ext
else
set fixedName to fileName
end if
set AppleScript's text item delimiters to tids
return fixedName
end cleanFilename
Now if you want to automate this for a folder full of files you can use this code. Just replace lines 3 and 4 of the above script with this. I didn't check this code but it's simple enough it should work as-is.
NOTE: you don't need to worry if non-image files are in the folder you choose with this code because they won't (I'm assuming this) have the DxxPxx number sequence and thus this script will not change them in any way.
set theFolder to choose folder
tell application "Finder"
set theFiles to files of theFolder
repeat with aFile in theFiles
set thisName to name of aFile
set newName to my cleanFilename(thisName)
if newName is not thisName then
set name of aFile to newName
end if
end repeat
end tell

Resources