Ask the Script Doctor: Working with text

Today's Best Tech Deals

Picked by Macworld's Editors

Top Deals On Great Products

Picked by Techconnect's Editors

Ask the Script Doctor is a regular column in which we solve real-world Mac problems using AppleScript and Automator. If you have a problem you’d like us to solve, send an email to the Script Doctor for consideration.

Whether we’re writing novels or email, we all use text all the time. AppleScript is a great tool for making text-focused work easier and more efficient. For that reason, I get a lot of questions about how to simplify common text tasks. Here are a few of those questions and my answers.

Q: I write a lot of text, and I would love to simplify some of the things I do over and over—wrapping selected text in quotation marks, for example. Any suggestions?

The way to do this (and other similar tasks) is to create a service; then, you can select the text you want to wrap, and run the service to make the change. Unfortunately, OS X doesn’t let you save AppleScripts as services. But I can recommend two other tools that will get the job done.

Automator: Open Automator, select service as the type of document you want to create, and then click Choose. In the editing window, select text from the 'Service receives selected' drop-down and put a checkmark in the Output replaces selected text box. Next, drag the Run AppleScript action from the list on the left into the editing pane. (Enter AppleScript in the search window to make this easier.) Replace the default script text with:

on run {input, parameters}
  return "\"" & input & "\"" as string
end run

When you save the workflow, it will show up in the Application > Services menu (and in the contextual menu in apps that support contextual services) when you have selected text. Choose that service, and your selected text will be wrapped in quotation marks. To use this same script to wrap text with something else, replace "\"" with your own wrapper. (The structure of the replacement string is: quotation mark, wrapper, quotation mark. In the example above, we have to put a slash in front of the second quotation mark to indicate that we want to use it as a literal character.)

ThisService: Services created with Automator have a tendency to be slow. If you want something faster, I recommend the utility ThisService (free). To use it, open AppleScript Editor, enter the script below, and save it as a compiled script.

on process(input)
  return "\"" & input & "\"" as string
end process

Next, launch ThisService, point it to your script file, enable the Takes Input and Produces Output checkboxes, give it a name, and pack it up. The utility will convert the script into a service and install it for you automatically. The service will now show up in the Services menus, and you can trigger it at any time to wrap selected text in quotation marks.

Q: When doing my accounting, I often end up with a list of numbers in a text file.  I need to add these together to arrive at a total.  I’d love to be able to copy the entire list of numbers to the clipboard and just trigger a script to add them. Can this be done?

The Standard Additions scripting addition (an extension for AppleScript, which comes with OS X) includes commands for getting and setting the contents of the clipboard. So, to accomplish this task, you just need to retrieve the paragraphs on the clipboard, loop through them, and add them together. The example below does that and displays an alert when finished. Note the try statement in the script: If any paragraphs in the copied text aren’t numbers, this statement will prevent them from causing an error or being added to the total.

--Get the paragraphs of the text on the clipboard
set theParagraphs to paragraphs of (the clipboard)
--Initialize a variable for the total
set theTotal to 0
--Loop through the paragraphs of text
repeat with aParagraph in theParagraphs
  --Try to add the current paragraph to the total
    set theTotal to theTotal + aParagraph
  end try
end repeat
--Put the total back on the clipboard
set the clipboard to theTotal as string
--Alert the user that the paragraphs have been added
display alert "Clipboard Paragraphs Added." message "The total of " & theTotal & " was copied back to the clipboard."

Q: Is there a script that would let me convert a bunch of Microsoft Word documents inside a folder to plain-text format?

You’re in luck: Microsoft Word has extensive scripting support for opening, manipulating, and saving documents. The script below asks for a folder of Word documents and an output folder. It loops through the files in the chosen folder, opens them in Word, and then saves them into the output folder as text files.

--Ask for a folder of Word documents
set theFolder to choose folder with prompt "Select a folder of Word documents:"
--Ask for an output folder
set theOutputFolder to choose folder with prompt "Select an output folder:"
--Get a list of documents in the chosen folder
tell application "Finder" to set theDocuments to every file of theFolder
--Loop through the detected documents
repeat with aDocument in theDocuments
  --Convert the current document to an AppleScript alias, rather than a Finder reference
  set aDocument to aDocument as alias
  --Get the name and extension of the document
  set theName to displayed name of (info for aDocument)
  set theExtension to name extension of (info for aDocument)
  --Get the name without the extension
  if theName ends with "." & theExtension then set theName to text 1 thru -(length of theExtension) of theName
  --Prepare the save path
  set theOutputFile to ((theOutputFolder as string) & theName & ".txt")
  --Make sure an existing file isn't overwritten
  tell application "Finder"
    if file theOutputFile exists then error "Existing file found."
  end tell
  --Open the document
  tell application "Microsoft Word"
    open aDocument
    --Save the document into the chosen output folder as text
    tell active document
      save as file format format text file name theOutputFile
      --Close the original document without saving
      close saving no
    end tell
  end tell
end repeat

Have a problem for the Script Doctor? Send it to

Note: When you purchase something after clicking links in our articles, we may earn a small commission. Read our affiliate link policy for more details.
Shop Tech Products at Amazon