TweetFollow Us on Twitter

Working With Text

Volume Number: 21 (2005)
Issue Number: 7
Column Tag: Programming

AppleScript Essentials

Working With Text

by Benjamin S. Waldie

When writing AppleScript code, many of the things that you will automate will involve working with and manipulating text in some manner. For example, you might need to write a script that will retrieve text content from a FileMaker Pro database, and then place that content into an Adobe InDesign document. You may need to maintain a text-based log file of your script's activity during processing, or you may need a script that will extract content from email messages, and write the content to files on a server.

During this month's article, we will discuss a number of ways to work with text, including ways to break text apart, search text, and read from and write to files.

About Text in AppleScript

Much like a scriptable application in the Mac OS, the AppleScript language itself possesses classes and commands. These classes and commands are considered to be the core language of AppleScript, and are used, interspersed with application and scripting addition terminology, to make up your scripts. For a detailed overview of AppleScript's core language, you should refer to The AppleScript Language Guide, which is available through Apple's Developer Connection at http://developer.apple.com/documentation/AppleScript/.

In AppleScript, text is considered to be a class, and is synonymous with the class string. Because of this, throughout this article, I will use the term string when referring to text.

class of ("This is some text" as text)
--> string

Just like classes in applications, AppleScript core language classes can possess properties. A string possesses a length property, which may be used in order to determine the number of characters contained within the string. For example:

length of "This is some text"
--> 17

Manipulating Text

When working with a string in AppleScript, one of the things that you will probably want to do is to manipulate it, or break it apart in some way. For example, you might need to write code that will parse a tab-delimited file, extracting field information. Once broken apart, it can be repurposed, merged back together in various ways, and more.

Elements of a String

In AppleScript, paragraphs, words, characters, and text are all considered to be elements of the class string. Because of this, a string can be broken up in a number of different ways. The following examples show some of the ways that a string can be broken up by referencing its elements.

The following example code will retrieve a paragraph from a specified string:

set theText to "This is paragraph 1 of some text.
This is paragraph 2 of some text."

set theParagraph to paragraph 2 of theText
--> "This is paragraph 2 of some text."

The following example code will retrieve a word from the string specified above:

word 3 of theText
--> "paragraph"

The following example code will retrieve a character from the string specified above:

character 9 of theText
--> "p"

You may also choose to retrieve multiple elements of a string at once. The following code will retrieve a specified set of characters from the string specified above:

characters 1 thru 9 of theText
--> {"T", "h", "i", "s", " ", "i", "s", " ", "p"}

When retrieving elements in this manner, you will notice that the result is provided as a list. When retrieving words or paragraphs in this manner, a list may suffice. However, when retrieving characters, you may prefer a string instead. To retrieve a list of characters as a string, you could coerce the retrieved list back to a string. You could also reference the text element of the string, rather than the character element. For example:

(characters 1 thru 9 of theText) as string
--> "This is p"

text 1 thru 9 of theText
--> "This is p"

Using the Offset Command

At times, you may need to determine the location of a specific character, word, or string within a longer string. While this could be accomplished by using a repeat statement to loop through the characters of the string until the specified search string is found, a more efficient way would be to use the offset command. The offset command is included in the String Commands suite in the Standard Additions scripting addition that is installed with Mac OS X.

set theFileName to "filename.jpg"

offset of "." in theFileName
--> 9

As you can see from the example code above, the offset command will return the position of the first instance of a specified string within another string. With this value, you can then retrieve specific parts of the string. For example, the following sample code will extract the prefix before a specified character in the string that we used above.

text 1 thru (offset of "." in theFileName) of theFileName
--> "filename."

Note in the example above, that the extracted prefix actually contains the delimiter character. Again, this is because the offset command will return the actual position of the first instance of the specified string. In order to extract the prefix without the delimiter, then you must subtract 1 from the offset. For example:

set thePrefix to text 1 thru ((offset of "." in theFileName) - 1) of theFileName
--> "filename"

You may also add 1 to the offset, and extract text from that location until the end of the string, in order to retrieve the suffix following the delimiter. For example:

set theSuffix to text ((offset of "." in theFileName) + 1) thru -1 of theFileName
--> "jpg"

Again, the offset command will return the position of only the first instance of a specified string. However, what if a string contains multiple delimiters, and you want to break the text apart based on the offset of the last delimiter? To do this, you can extract the characters of the string in list format, then reverse them using the reverse property of a list. Next, you can change the reversed characters back to a string, extract the prefix and suffix, and then reverse them back. This sounds complicated, but it can actually be done in only a few lines of code. The following example code will walk you through the process.

This example code will extract the characters of the string:

set theFileName to "file.name.jpg"
set theCharacters to characters of theFileName
--> {"f", "i", "l", "e", ".", "n", "a", "m", "e", ".", "j", "p", "g"}

This example code will reverse the extracted characters:

set theReversedCharacters to reverse of theCharacters
--> {"g", "p", "j", ".", "e", "m", "a", "n", ".", "e", "l", "i", "f"}

This example code will convert the reversed characters back to a string:

set theReversedFileName to theReversedCharacters as string
--> "gpj.eman.elif"

This example code will locate the delimiter in the reversed string, using the offset command:

set theOffset to offset of "." in theReversedFileName
--> 4

This example code will retrieve the prefix and suffix from the reversed string:

set theReversedSuffix to text 1 thru (theOffset - 1) of theReversedFileName
--> "gpj"

set theReversedPrefix to text (theOffset + 1) thru -1 of theReversedFileName
--> "eman.elif"

This example code will reverse the extracted prefix and suffix back to their original form:

set thePrefix to (reverse of (characters of theReversedPrefix)) as string
--> "file.name"

set theSuffix to (reverse of (characters of theReversedSuffix)) as string
--> "jpg"

Now, you should have the properly retrieved prefix and suffix. The example code above could actually have been written in a more condensed fashion. It was intentionally written in a verbose manner for demonstration purposes. For example, the following code will perform the same function, but has been condensed into fewer lines of code:

set theFileName to "file.name.jpg"
set theReversedFileName to (reverse of (characters of theFileName)) as string
set theOffset to offset of "." in theReversedFileName
set thePrefix to (reverse of (characters (theOffset + 1) 
   thru -1 of theReversedFileName)) as string
set theSuffix to (reverse of (characters 1 thru (theOffset - 1) 
   of theReversedFileName)) as string

Another thing to note when working with the offset command is that in some cases, you may attempt to get the offset of a string that does not exist with the string you are evaluating. If this occurs, the offset command will return a value of 0. For example:

offset of "." in "filename"
--> 0

As you begin using the offset command, be sure to add code to handle this type of situation, should it occur.

Using AppleScript's Text Item Delimiters

Another way of breaking text apart is by making use of AppleScript's text item delimiters property, which is actually a property of AppleScript itself, and can be retrieved or changed at any time. AppleScript's text item delimiters property contains the delimiter that is used to separate chunks of text within a string. By default, AppleScript's text item delimiters property is set to a value of {""}, essentially an empty string.

Though AppleScript's text item delimiters may be set to a list containing multiple values, AppleScript will only utilize the first value in the list. For this reason, when setting AppleScript's text item delimiters, it is not necessary to specify a list. Rather, a string may be used, as you will see in the next code example.

AppleScript's text item delimiters
--> {""}

A character is the smallest element within a string. Since AppleScript's text item delimiters are set to an empty string by default, retrieving the text elements from a string will return the characters from within that string in list format.

The following example code will demonstrate how AppleScript's text item delimiters may be changed in order to break apart a string. Please note that modifying this property of AppleScript may affect other code in your script. Therefore, you should always be sure to set the value of the property back to its default value when you are done manipulating your string.

set theText to "01.01.2005"
set AppleScript's text item delimiters to "."
set theTextItems to text items of theText
set AppleScript's text item delimiters to {""}
theTextItems
--> {"01", "01", "2005"}

As you can see, the example code above can be used to convert a string to a list, using a specified delimiter. So, using this method, you could easily write code that would convert a tab delimited string into a list of fields.

The AppleScript's text item delimiters property may also be used to coerce a list of values back to a string. The following example code will take the list output by the previous example, and change it back to a string, using a different delimiter.

set theTextItems to {"01", "01", "2005"}
set AppleScript's text item delimiters to "-"
set theText to theTextItems as string
set AppleScript's text item delimiters to {""}
theText
--> "01-01-2005"

Now that we have explored ways to convert a string to a list and back, we can take things a step further. The following example code will perform a find and replace within a string.

set theText to "01-01-2005"
set AppleScript's text item delimiters to "-"
set theTextItems to text items of theText
set AppleScript's text item delimiters to "/"
set theText to theTextItems as string
set AppleScript's text item delimiters to {""}
theText
--> "01/01/2005"

In the example code above, every instance of the "-" character is replaced with the "/" character.

In all of the examples above, we were working with a single character as our delimiter. If desired, you may set AppleScript's text item delimiters to a longer string containing multiple characters, such as a word or a paragraph.

Reading and Writing Text

Now that we have explored several ways to break apart and manipulate text, let's discuss ways to work with files through reading and writing.

Reading from a File

Reading from a file is done using a command found in the File Read/Write suite of the Standard Additions scripting addition. To read from a file, use the read command.

set theFile to choose file with prompt "Select a text file:"
read theFile

The example code above will prompt you to select a text file. Next, it will read the file and return the entire contents of the file as a string.

When reading from a file, you may optionally choose to use the open for access command, also found in the File Read/Write suite, to open a file, prior to reading from it. By using this command to open a file prior to reading from it, the file will remain opened in memory until the script closes the file, using the close access command. For example:

set theFile to choose file with prompt "Select a text file:"
set theFileReference to open for access theFile
set theFileContents to read theFileReference
close access theFileReference

As you can see from the example code above, the open for access command returns a reference to the opened file. That reference can then be used to refer to the opened file, using the read and close access commands. It is important to always use the close access command when you are done working with a file. Otherwise, the file will remain opened, and may not be opened for access again until it is closed. This can potentially produce error messages in subsequent runs of the script.

When reading from a file, the read command offers some optional parameters. For best results with these parameters, you should use the open for access and close access commands, along with the read command. The from and to parameters will allow you to read a small portion of the file's contents. For example, the following example code will read a file up until the 10th character:

set theFile to choose file with prompt "Select a text file:"
set theFileReference to open for access theFile
set theFileContents to read theFileReference to 10
close access theFileReference

The following example code will read a file between two specified characters, in this case, the text between character 10 and character 20:

set theFile to choose file with prompt "Select a text file:"
set theFileReference to open for access theFile
set theFileContents to read theFileReference from 10 to 20
close access theFileReference

The until parameter will allow you to read a file until a specific character is detected. For example, the code below will read a file until a return character is detected.

set theFile to choose file with prompt "Select a text file:"
set theFileReference to open for access theFile
set theFileContents to read theFileReference until return
close access theFileReference

The using delimiter and using delimiters parameters will allow you to read a file using one or more specified delimiters. The result will be a list of strings, broken apart by the specified delimiter(s). This may be useful when reading a tab-delimited file directly, as it would allow you to break apart the file as it is read by the script. For example:

set theFile to choose file with prompt "Select a text file:"
set theFileReference to open for access theFile
set theFileContents to read theFileReference using delimiter tab
close access theFileReference

Some of optional parameters shown above possess additional functionalities that were not covered in this article. In addition, the read command also includes some other optional parameters, which may be useful in other situations. I encourage you to spend some additional time becoming familiar with all of the optional parameters of the read command.

Writing to a File

To write data to a file, you use the write command, also found in the File Read/Write suite. When using the write command, it is always necessary to use the open for access command prior to writing to the file. You cannot write to a file unless it has been opened first. In addition, when opening a file for writing, you must also specify the with write permission optional parameter for the open for access command. Otherwise, the file will be opened, but you will not be able to write to it.

The following example code will prompt the user to enter some text, and then write that text to a file on the desktop.

set theText to text returned of (display dialog "Please enter some text:" default answer "")
set theFilePath to (path to desktop as string) & "test.txt" as string
set theFileReference to open for access theFilePath with write permission
write theText to theFileReference
close access theFileReference

Like the read command, the write command also has some optional parameters, including the starting at parameter. This parameter will allow you to specify at what point in the file to begin writing. By default, the write command will start writing at the beginning of a file. To start writing at the end of a file, you may use the term eof, for end of file. You may also specify a numeric value for the starting at parameter, specifying the number of the character at which the script should begin writing.

The following example code will append a specified string to the end of a file:

set theText to text returned of (display dialog "Please enter some text:" default answer "")
set theFilePath to (path to desktop as string) & "test.txt" as string
set theFileReference to open for access theFilePath with write permission
write theText to theFileReference starting at eof
close access theFileReference

Optionally, you may want to use the set eof command, also found in the File Read/Write suite, in order to change the location of the end of the file. For example, the following code will set the end of the file to 0, wiping all existing content, prior to writing the new text.

set theText to text returned of (display dialog "Please enter some text:" default answer "")
set theFilePath to (path to desktop as string) & "test.txt" as string
set theFileReference to open for access theFilePath with write permission
set eof of theFileReference to 0
write theText to theFileReference starting at eof
close access theFileReference

In Closing

Now that we have explored some of the ways that you can manipulate text content, you can begin to experiment with these methods, and combine them together in order to perform more robust types of processing. For example, try creating a handler that will write specified content to a text file. Then, call that handler throughout a script to maintain a running activity log. You may find such a log to be useful in monitoring the script's activity, as well as for troubleshooting purposes.

For continued learning about working with text, be sure to review the AppleScript Language Guide, mentioned earlier. You will also find detailed documentation and additional examples in most AppleScript books, such as Danny Goodman's AppleScript Handbook, available from SpiderWorks, LLC at http://www.spiderworks.com.

Until next time, keep scripting!


Benjamin Waldie is president of Automated Workflows, LLC, a firm specializing in AppleScript and workflow automation consulting. In addition to his role as a consultant, Benjamin is an evangelist of AppleScript, and can frequently be seen presenting at Macintosh User Groups, Seybold Seminars, and MacWorld. For additional information about Benjamin, please visit http://www.automatedworkflows.com, or email Benjamin at applescriptguru@mac.com.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

The Legend of Heroes: Trails of Cold Ste...
I adore game series that have connecting lore and stories, which of course means the Legend of Heroes is very dear to me, Trails lore has been building for two decades. Excitedly, the next stage is upon us as Userjoy has announced the upcoming... | Read more »
Go from lowly lizard to wicked Wyvern in...
Do you like questing, and do you like dragons? If not then boy is this not the announcement for you, as Loongcheer Game has unveiled Quest Dragon: Idle Mobile Game. Yes, it is amazing Square Enix hasn’t sued them for copyright infringement, but... | Read more »
Aether Gazer unveils Chapter 16 of its m...
After a bit of maintenance, Aether Gazer has released Chapter 16 of its main storyline, titled Night Parade of the Beasts. This big update brings a new character, a special outfit, some special limited-time events, and, of course, an engaging... | Read more »
Challenge those pesky wyverns to a dance...
After recently having you do battle against your foes by wildly flailing Hello Kitty and friends at them, GungHo Online has whipped out another surprising collaboration for Puzzle & Dragons. It is now time to beat your opponents by cha-cha... | Read more »
Pack a magnifying glass and practice you...
Somehow it has already been a year since Torchlight: Infinite launched, and XD Games is celebrating by blending in what sounds like a truly fantastic new update. Fans of Cthulhu rejoice, as Whispering Mist brings some horror elements, and tests... | Read more »
Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »

Price Scanner via MacPrices.net

Apple is offering significant discounts on 16...
Apple has a full line of 16″ M3 Pro and M3 Max MacBook Pros available, Certified Refurbished, starting at $2119 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free... Read more
Apple HomePods on sale for $30-$50 off MSRP t...
Best Buy is offering a $30-$50 discount on Apple HomePods this weekend on their online store. The HomePod mini is on sale for $69.99, $30 off MSRP, while Best Buy has the full-size HomePod on sale... Read more
Limited-time sale: 13-inch M3 MacBook Airs fo...
Amazon has the base 13″ M3 MacBook Air (8GB/256GB) in stock and on sale for a limited time for $989 shipped. That’s $110 off MSRP, and it’s the lowest price we’ve seen so far for an M3-powered... Read more
13-inch M2 MacBook Airs in stock today at App...
Apple has 13″ M2 MacBook Airs available for only $849 today in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty is included,... Read more
New today at Apple: Series 9 Watches availabl...
Apple is now offering Certified Refurbished Apple Watch Series 9 models on their online store for up to $80 off MSRP, starting at $339. Each Watch includes Apple’s standard one-year warranty, a new... Read more
The latest Apple iPhone deals from wireless c...
We’ve updated our iPhone Price Tracker with the latest carrier deals on Apple’s iPhone 15 family of smartphones as well as previous models including the iPhone 14, 13, 12, 11, and SE. Use our price... Read more
Boost Mobile will sell you an iPhone 11 for $...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering an iPhone 11 for $149.99 when purchased with their $40 Unlimited service plan (12GB of premium data). No trade-in is required... Read more
Free iPhone 15 plus Unlimited service for $60...
Boost Infinite, part of MVNO Boost Mobile using AT&T and T-Mobile’s networks, is offering a free 128GB iPhone 15 for $60 per month including their Unlimited service plan (30GB of premium data).... Read more
$300 off any new iPhone with service at Red P...
Red Pocket Mobile has new Apple iPhones on sale for $300 off MSRP when you switch and open up a new line of service. Red Pocket Mobile is a nationwide MVNO using all the major wireless carrier... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, available for $759 for 8-Core CPU/7-Core GPU/256GB models and $929 for 8-Core CPU/8-Core GPU/512GB models. Apple’s one-year warranty is... Read more

Jobs Board

DMR Technician - *Apple* /iOS Systems - Haml...
…relevant point-of-need technology self-help aids are available as appropriate. ** Apple Systems Administration** **:** Develops solutions for supporting, deploying, Read more
Operating Room Assistant - *Apple* Hill Sur...
Operating Room Assistant - Apple Hill Surgical Center - Day Location: WellSpan Health, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Read more
Solutions Engineer - *Apple* - SHI (United...
**Job Summary** An Apple Solution Engineer's primary role is tosupport SHI customers in their efforts to select, deploy, and manage Apple operating systems and Read more
DMR Technician - *Apple* /iOS Systems - Haml...
…relevant point-of-need technology self-help aids are available as appropriate. ** Apple Systems Administration** **:** Develops solutions for supporting, deploying, Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.