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

LaunchBar 6.18.5 - Powerful file/URL/ema...
LaunchBar is an award-winning productivity utility that offers an amazingly intuitive and efficient way to search and access any kind of information stored on your computer or on the Web. It provides... Read more
Affinity Designer 2.3.0 - Vector graphic...
Affinity Designer is an incredibly accurate vector illustrator that feels fast and at home in the hands of creative professionals. It intuitively combines rock solid and crisp vector art with... Read more
Affinity Photo 2.3.0 - Digital editing f...
Affinity Photo - redefines the boundaries for professional photo editing software for the Mac. With a meticulous focus on workflow it offers sophisticated tools for enhancing, editing and retouching... Read more
WhatsApp 23.24.78 - Desktop client for W...
WhatsApp is the desktop client for WhatsApp Messenger, a cross-platform mobile messaging app which allows you to exchange messages without having to pay for SMS. WhatsApp Messenger is available for... Read more
Adobe Photoshop 25.2 - Professional imag...
You can download Adobe Photoshop as a part of Creative Cloud for only $54.99/month Adobe Photoshop is a recognized classic of photo-enhancing software. It offers a broad spectrum of tools that can... Read more
PDFKey Pro 4.5.1 - Edit and print passwo...
PDFKey Pro can unlock PDF documents protected for printing and copying when you've forgotten your password. It can now also protect your PDF files with a password to prevent unauthorized access and/... Read more
Skype 8.109.0.209 - Voice-over-internet...
Skype is a telecommunications app that provides HD video calls, instant messaging, calling to any phone number or landline, and Skype for Business for productive cooperation on the projects. This... Read more
OnyX 4.5.3 - Maintenance and optimizatio...
OnyX is a multifunction utility that you can use to verify the startup disk and the structure of its system files, to run miscellaneous maintenance and cleaning tasks, to configure parameters in the... Read more
CrossOver 23.7.0 - Run Windows apps on y...
CrossOver can get your Windows productivity applications and PC games up and running on your Mac quickly and easily. CrossOver runs the Windows software that you need on Mac at home, in the office,... Read more
Tower 10.2.1 - Version control with Git...
Tower is a Git client for OS X that makes using Git easy and more efficient. Users benefit from its elegant and comprehensive interface and a feature set that lets them enjoy the full power of Git.... Read more

Latest Forum Discussions

See All

Pour One Out for Black Friday – The Touc...
After taking Thanksgiving week off we’re back with another action-packed episode of The TouchArcade Show! Well, maybe not quite action-packed, but certainly discussion-packed! The topics might sound familiar to you: The new Steam Deck OLED, the... | Read more »
TouchArcade Game of the Week: ‘Hitman: B...
Nowadays, with where I’m at in my life with a family and plenty of responsibilities outside of gaming, I kind of appreciate the smaller-scale mobile games a bit more since more of my “serious" gaming is now done on a Steam Deck or Nintendo Switch.... | Read more »
SwitchArcade Round-Up: ‘Batman: Arkham T...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for December 1st, 2023. We’ve got a lot of big games hitting today, new DLC For Samba de Amigo, and this is probably going to be the last day this year with so many heavy hitters. I... | Read more »
Steam Deck Weekly: Tales of Arise Beyond...
Last week, there was a ton of Steam Deck coverage over here focused on the Steam Deck OLED. | Read more »
World of Tanks Blitz adds celebrity amba...
Wargaming is celebrating the season within World of Tanks Blitz with a new celebrity ambassador joining this year's Holiday Ops. In particular, British footballer and movie star Vinnie Jones will be brightening up the game with plenty of themed in-... | Read more »
KartRider Drift secures collaboration wi...
Nexon and Nitro Studios have kicked off the fifth Season of their platform racer, KartRider Dift, in quite a big way. As well as a bevvy of new tracks to take your skills to, and the new racing pass with its rewards, KartRider has also teamed up... | Read more »
‘SaGa Emerald Beyond’ From Square Enix G...
One of my most-anticipated releases of 2024 is Square Enix’s brand-new SaGa game which was announced during a Nintendo Direct. SaGa Emerald Beyond will launch next year for iOS, Android, Switch, Steam, PS5, and PS4 featuring 17 worlds that can be... | Read more »
Apple Arcade Weekly Round-Up: Updates fo...
This week, there is no new release for Apple Arcade, but many notable games have gotten updates ahead of next week’s holiday set of games. If you haven’t followed it, we are getting a brand-new 3D Sonic game exclusive to Apple Arcade on December... | Read more »
New ‘Honkai Star Rail’ Version 1.5 Phase...
The major Honkai Star Rail’s 1.5 update “The Crepuscule Zone" recently released on all platforms bringing in the Fyxestroll Garden new location in the Xianzhou Luofu which features many paranormal cases, players forming a ghost-hunting squad,... | Read more »
SwitchArcade Round-Up: ‘Arcadian Atlas’,...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for November 30th, 2023. It’s Thursday, and unlike last Thursday this is a regular-sized big-pants release day. If you like video games, and I have to believe you do, you’ll want to... | Read more »

Price Scanner via MacPrices.net

Deal Alert! Apple Smart Folio Keyboard for iP...
Apple iPad Smart Keyboard Folio prices are on Holiday sale for only $79 at Amazon, or 50% off MSRP: – iPad Smart Folio Keyboard for iPad (7th-9th gen)/iPad Air (3rd gen): $79 $79 (50%) off MSRP This... Read more
Apple Watch Series 9 models are now on Holida...
Walmart has Apple Watch Series 9 models now on Holiday sale for $70 off MSRP on their online store. Sale prices available for online orders only, in-store prices may vary. Order online, and choose... Read more
Holiday sale this weekend at Xfinity Mobile:...
Switch to Xfinity Mobile (Mobile Virtual Network Operator..using Verizon’s network) and save $500 instantly on any iPhone 15, 14, or 13 and up to $800 off with eligible trade-in. The total is applied... Read more
13-inch M2 MacBook Airs with 512GB of storage...
Best Buy has the 13″ M2 MacBook Air with 512GB of storage on Holiday sale this weekend for $220 off MSRP on their online store. Sale price is $1179. Price valid for online orders only, in-store price... Read more
B&H Photo has Apple’s 14-inch M3/M3 Pro/M...
B&H Photo has new Gray and Black 14″ M3, M3 Pro, and M3 Max MacBook Pros on Holiday sale this weekend for $100-$200 off MSRP, starting at only $1499. B&H offers free 1-2 day delivery to most... Read more
15-inch M2 MacBook Airs are $200 off MSRP on...
Best Buy has Apple 15″ MacBook Airs with M2 CPUs in stock and on Holiday sale for $200 off MSRP on their online store. Their prices are among the lowest currently available for new 15″ M2 MacBook... Read more
Get a 9th-generation Apple iPad for only $249...
Walmart has Apple’s 9th generation 10.2″ iPads on sale for $80 off MSRP on their online store as part of their Cyber Week Holiday sale, only $249. Their prices are the lowest new prices available for... Read more
Space Gray Apple AirPods Max headphones are o...
Amazon has Apple AirPods Max headphones in stock and on Holiday sale for $100 off MSRP. The sale price is valid for Space Gray at the time of this post. Shipping is free: – AirPods Max (Space Gray... Read more
Apple AirTags 4-Pack back on Holiday sale for...
Amazon has Apple AirTags 4 Pack back on Holiday sale for $79.99 including free shipping. That’s 19% ($20) off Apple’s MSRP. Their price is the lowest available for 4 Pack AirTags from any of the... Read more
New Holiday promo at Verizon: Buy one set of...
Looking for more than one set of Apple AirPods this Holiday shopping season? Verizon has a great deal for you. From today through December 31st, buy one set of AirPods on Verizon’s online store, and... Read more

Jobs Board

Senior Software Engineer - *Apple* Fundamen...
…center of Microsoft's efforts to empower our users to do more. The Apple Fundamentals team focused on defining and improving the end-to-end developer experience in 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
Housekeeper, *Apple* Valley Villa - Cassia...
Apple Valley Villa, part of a senior living community, is hiring entry-level Full-Time Housekeepers to join our team! We will train you for this position and offer a Read more
Senior Manager, Product Management - *Apple*...
…Responsibilities** We are seeking an ambitious, data-driven thinker to assist the Apple Product Development team as our Wireless Product division continues to grow Read more
Mobile Platform Engineer ( *Apple* /AirWatch)...
…systems, installing and maintaining certificates, navigating multiple network segments and Apple /IOS devices, Mobile Device Management systems such as AirWatch, and Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.