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

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 »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »
MoreFun Studios has announced Season 4,...
Tension has escalated in the ever-volatile world of Arena Breakout, as your old pal Randall Fisher and bosses Fred and Perrero continue to lob insults and explosives at each other, bringing us to a new phase of warfare. Season 4, Into The Fog of... | Read more »
Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links below... | Read more »
Marvel Future Fight celebrates nine year...
Announced alongside an advertising image I can only assume was aimed squarely at myself with the prominent Deadpool and Odin featured on it, Netmarble has revealed their celebrations for the 9th anniversary of Marvel Future Fight. The Countdown... | Read more »
HoYoFair 2024 prepares to showcase over...
To say Genshin Impact took the world by storm when it was released would be an understatement. However, I think the most surprising part of the launch was just how much further it went than gaming. There have been concerts, art shows, massive... | Read more »

Price Scanner via MacPrices.net

Amazon is offering a $100 discount on every M...
Amazon is offering a $100 instant discount on each configuration of Apple’s new 13″ M3 MacBook Air, in Midnight, this weekend. These are the lowest prices currently available for new 13″ M3 MacBook... Read more
You can save $300-$480 on a 14-inch M3 Pro/Ma...
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
24-inch M1 iMacs available at Apple starting...
Apple has clearance M1 iMacs available in their Certified Refurbished store starting at $1049 and ranging up to $300 off original MSRP. Each iMac is in like-new condition and comes with Apple’s... Read more
Walmart continues to offer $699 13-inch M1 Ma...
Walmart continues to offer 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 MacBook for sale by... Read more
B&H has 13-inch M2 MacBook Airs with 16GB...
B&H Photo has 13″ MacBook Airs with M2 CPUs, 16GB of memory, and 256GB of storage in stock and on sale for $1099, $100 off Apple’s MSRP for this configuration. Free 1-2 day delivery is available... Read more
14-inch M3 MacBook Pro with 16GB of RAM avail...
Apple has the 14″ M3 MacBook Pro with 16GB of RAM and 1TB of storage, Certified Refurbished, available for $300 off MSRP. Each MacBook Pro features a new outer case, shipping is free, and an Apple 1-... Read more
Apple M2 Mac minis on sale for up to $150 off...
Amazon has Apple’s M2-powered Mac minis in stock and on sale for $100-$150 off MSRP, each including free delivery: – Mac mini M2/256GB SSD: $499, save $100 – Mac mini M2/512GB SSD: $699, save $100 –... Read more
Amazon is offering a $200 discount on 14-inch...
Amazon has 14-inch M3 MacBook Pros in stock and on sale for $200 off MSRP. Shipping is free. Note that Amazon’s stock tends to come and go: – 14″ M3 MacBook Pro (8GB RAM/512GB SSD): $1399.99, $200... Read more
Sunday Sale: 13-inch M3 MacBook Air for $999,...
Several Apple retailers have the new 13″ MacBook Air with an M3 CPU in stock and on sale today for only $999 in Midnight. These are the lowest prices currently available for new 13″ M3 MacBook Airs... Read more
Multiple Apple retailers are offering 13-inch...
Several Apple retailers have 13″ MacBook Airs with M2 CPUs in stock and on sale this weekend starting at only $849 in Space Gray, Silver, Starlight, and Midnight colors. These are the lowest prices... Read more

Jobs Board

Relationship Banker - *Apple* Valley Financ...
Relationship Banker - Apple Valley Financial Center APPLE VALLEY, Minnesota **Job Description:** At Bank of America, we are guided by a common purpose to help Read more
IN6728 Optometrist- *Apple* Valley, CA- Tar...
Date: Apr 9, 2024 Brand: Target Optical Location: Apple Valley, CA, US, 92308 **Requisition ID:** 824398 At Target Optical, we help people see and look great - and Read more
Medical Assistant - Orthopedics *Apple* Hil...
Medical Assistant - Orthopedics Apple Hill York Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Now Read more
*Apple* Systems Administrator - JAMF - Activ...
…**Public Trust/Other Required:** None **Job Family:** Systems Administration **Skills:** Apple Platforms,Computer Servers,Jamf Pro **Experience:** 3 + years of Read more
Liquor Stock Clerk - S. *Apple* St. - Idaho...
Liquor Stock Clerk - S. Apple St. Boise Posting Begin Date: 2023/10/10 Posting End Date: 2024/10/14 Category: Retail Sub Category: Customer Service Work Type: Part Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.