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

Fresh From the Land Down Under – The Tou...
After a two week hiatus, we are back with another episode of The TouchArcade Show. Eli is fresh off his trip to Australia, which according to him is very similar to America but more upside down. Also kangaroos all over. Other topics this week... | Read more »
TouchArcade Game of the Week: ‘Dungeon T...
I’m a little conflicted on this week’s pick. Pretty much everyone knows the legend of Dungeon Raid, the match-3 RPG hybrid that took the world by storm way back in 2011. Everyone at the time was obsessed with it, but for whatever reason the... | Read more »
SwitchArcade Round-Up: Reviews Featuring...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for July 19th, 2024. In today’s article, we finish up the week with the unusual appearance of a review. I’ve spent my time with Hot Lap Racing, and I’m ready to give my verdict. After... | Read more »
Draknek Interview: Alan Hazelden on Thin...
Ever since I played my first release from Draknek & Friends years ago, I knew I wanted to sit down with Alan Hazelden and chat about the team, puzzle games, and much more. | Read more »
The Latest ‘Marvel Snap’ OTA Update Buff...
I don’t know about all of you, my fellow Marvel Snap (Free) players, but these days when I see a balance update I find myself clenching my… teeth and bracing for the impact to my decks. They’ve been pretty spicy of late, after all. How will the... | Read more »
‘Honkai Star Rail’ Version 2.4 “Finest D...
HoYoverse just announced the Honkai Star Rail (Free) version 2.4 “Finest Duel Under the Pristine Blue" update alongside a surprising collaboration. Honkai Star Rail 2.4 follows the 2.3 “Farewell, Penacony" update. Read about that here. | Read more »
‘Vampire Survivors+’ on Apple Arcade Wil...
Earlier this month, Apple revealed that poncle’s excellent Vampire Survivors+ () would be heading to Apple Arcade as a new App Store Great. I reached out to poncle to check in on the DLC for Vampire Survivors+ because only the first two DLCs were... | Read more »
Homerun Clash 2: Legends Derby opens for...
Since launching in 2018, Homerun Clash has performed admirably for HAEGIN, racking up 12 million players all eager to prove they could be the next baseball champions. Well, the title will soon be up for grabs again, as Homerun Clash 2: Legends... | Read more »
‘Neverness to Everness’ Is a Free To Pla...
Perfect World Games and Hotta Studio (Tower of Fantasy) announced a new free to play open world RPG in the form of Neverness to Everness a few days ago (via Gematsu). Neverness to Everness has an urban setting, and the two reveal trailers for it... | Read more »
Meditative Puzzler ‘Ouros’ Coming to iOS...
Ouros is a mediative puzzle game from developer Michael Kamm that launched on PC just a couple of months back, and today it has been revealed that the title is now heading to iOS and Android devices next month. Which is good news I say because this... | Read more »

Price Scanner via MacPrices.net

Amazon is still selling 16-inch MacBook Pros...
Prime Day in July is over, but Amazon is still selling 16-inch Apple MacBook Pros for $500-$600 off MSRP. Shipping is free. These are the lowest prices available this weekend for new 16″ Apple... Read more
Walmart continues to sell clearance 13-inch M...
Walmart continues to offer clearance, but new, Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBooks... Read more
Apple is offering steep discounts, up to $600...
Apple has standard-configuration 16″ M3 Max MacBook Pros available, Certified Refurbished, starting at $2969 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free,... Read more
Save up to $480 with these 14-inch M3 Pro/M3...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
Amazon has clearance 9th-generation WiFi iPad...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80-$100 off MSRP, starting only $249. Their prices are the lowest available for new iPads anywhere: – 10″ 64GB WiFi iPad (Space Gray or... Read more
Apple is offering a $50 discount on 2nd-gener...
Apple has Certified Refurbished White and Midnight HomePods available for $249, Certified Refurbished. That’s $50 off MSRP and the lowest price currently available for a full-size Apple HomePod today... Read more
The latest MacBook Pro sale at Amazon: 16-inc...
Amazon is offering instant discounts on 16″ M3 Pro and 16″ M3 Max MacBook Pros ranging up to $400 off MSRP as part of their early July 4th sale. Shipping is free. These are the lowest prices... Read more
14-inch M3 Pro MacBook Pros with 36GB of RAM...
B&H Photo has 14″ M3 Pro MacBook Pros with 36GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 Pro MacBook Pro (... Read more
14-inch M3 MacBook Pros with 16GB of RAM on s...
B&H Photo has 14″ M3 MacBook Pros with 16GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $150-$200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 MacBook Pro (... Read more
Amazon is offering $170-$200 discounts on new...
Amazon is offering a $170-$200 discount on every configuration and color of Apple’s M3-powered 15″ MacBook Airs. Prices start at $1129 for models with 8GB of RAM and 256GB of storage: – 15″ M3... Read more

Jobs Board

*Apple* Systems Engineer - Chenega Corporati...
…LLC,** a **Chenega Professional Services** ' company, is looking for a ** Apple Systems Engineer** to support the Information Technology Operations and Maintenance 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
*Apple* / Mac Administrator - JAMF Pro - Ame...
Amentum is seeking an ** Apple / Mac Administrator - JAMF Pro** to provide support with the Apple Ecosystem to include hardware and software to join our team and Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.