How to remove words or phrases from selected text using AppleScript

Is there a way to remove selected words or phrases from selected text via AppleScript? I have a lot of documents that get marked up and I would love to quickly select all the text and remove the common marked up words that are consistently used that I need removed from selected text in documents and emails.


This kind of was along the path but was too specific to folders in the Finder for me to modify it.

https://discussions.apple.com/thread/6628135


Posted on Jul 1, 2019 12:50 PM

Reply

Similar questions

22 replies

Jul 31, 2019 3:06 PM in response to skillet


skillet wrote:

Just curious if you just ran this as AppleScript on selected text (I use Keyboard Maestro) what would you remove?


For some reason I'm having trouble getting apps to recognize the Quick Action so I slapped together a "plain vanilla" AppleScript:


set text item delimiters to space
property itemsToRemove : "(1-DT) (2-TE) (3-FE) (4-IN) (5-IF) (6-CR)"
set theText to the clipboard
set userInput to text returned of (display dialog "Enter codes to remove (separated by space)" default answer itemsToRemove as text)
if userInput is "" then return
set itemsToRemove to text items of userInput
set text item delimiters to itemsToRemove
set textItems to text items of theText
set text item delimiters to ""
set textItemsAsText to textItems as text
set text item delimiters to space & space -- double space
set textItems to text items of textItemsAsText
set text item delimiters to space -- single space
set the clipboard to textItems as text



Select text and command-c to copy to clipboard. Run script. Paste "cleaned" text wherever. Plain text only. You lose styling. But it's simple (no Objective-C really needed) and it works well here. Should run well from KM.


SG


Jul 3, 2019 9:59 AM in response to VikingOSX

Below, is the code to replace selected parenthetical codes per requirements in a document, be that Pages v8.1, or Scrivener 3.1.2 on Mojave. This is its principal intent, though some success may be gained by specifying unique words of text that you want removed from the selection.


I am using AppleScript/Objective-C to cut down on pure AppleScript code, and take advantage of its text and array methods. As written now, the code returns plain text — so any original attributed text (B, I, U, URL) text content will be replaced by plain text that retains the font, font size, alignment, and spacing characteristics. The code that would preserve and return full attributed text without specified text strings is another time consuming, coding exercise altogether. It would also require smart detection of the user input strings to determine how to branch processing of these respective inputs.


Replace the content of an Automator Quick Action, Run AppleScript action with the following code:


use framework "Foundation"
use AppleScript version "2.4" -- Yosemite 10.10 or later
use scripting additions

property NSString : a reference to current application's NSString
property NSCharacterSet : a reference to current application's NSCharacterSet
property NSArray : a reference to current application's NSArray
-- split exclude codes on this variety/mixture of separator characters
property DELIM : ",|; "

on run {input, parameters}
	
	try
		set user_input to text returned of (display dialog "Enter parenthetical codes to remove: " default answer "")
	on error errmsg number errnbr
		return
	end try
	
	if user_input's length = 0 then return
	
	return my remove_words(input as text, user_input) as text
end run

on remove_words(seltxt, utxt)
	-- inputs: 1) seltxt is the original user selected document text
	--            2) utxt is the string of parenthetical codes provided by the user
	-- returns the selected text without the user specified codes
	set theText to NSString's alloc()'s initWithString:seltxt
	set uStr to NSString's alloc()'s initWithString:utxt
	-- allow flexibility of input code separator characters
	set exCodes to NSCharacterSet's characterSetWithCharactersInString:DELIM
	-- split the user code text string into array elements based on DELIM chars
	set excludes to uStr's componentsSeparatedByCharactersInSet:exCodes
	set txtArray to (theText's componentsSeparatedByString:" ")'s mutableCopy()
	txtArray's removeObjectsInArray:excludes
	return (txtArray's componentsJoinedByString:" ") as text
end remove_words


The Quick Action looks like the following, and once saved with a meaningful name, it is available from the application's Service menu:


Jul 1, 2019 1:15 PM in response to skillet

I feel there is more to this problem than I have answered. We are in need of more details on what you are attempting to modify. Be specific. Split problem down to each document type you wish to change.


Are you looking to change an Applescript string/text?


I wrote up an alterString function. In this example, I changed all instances of BTS to bts and remove SNAP/.


(*SearchString is MF65BS00063RD3OS.PSD,MF65BS00063RD3OS,,BTS DTI SNAP/PONIO B BURGUNDY ONE SIZE,*)
(*in ~~~ alterString ~~~*)
(*SearchString is MF65BS00063RD3OS.PSD,MF65BS00063RD3OS,,bts DTI SNAP/PONIO B BURGUNDY ONE SIZE,*)
(*in ~~~ alterString ~~~*)
(*SearchString is MF65BS00063RD3OS.PSD,MF65BS00063RD3OS,,bts DTI PONIO B BURGUNDY ONE SIZE,*)



(* 

    It is easier to diagnose problems with debug information. I suggest adding 
    log statements to your script to see what is going on.  Here is an example.


	Author: rccharles
	
	For testing, run in the Script Editor.
	  1) Click on the Event Log tab to see the output from the log statement
	  2) Click on Run
	  
	For running shell commands see:
	https://developer.apple.com/library/archive/technotes/tn2065/_index.html
	http://developer.apple.com/mac/library/technotes/tn2002/tn2065.html
	


 *)
global debug
set debug to 5


set SearchString to "MF65BS00063RD3OS.PSD,MF65BS00063RD3OS,,BTS DTI SNAP/PONIO B BURGUNDY ONE SIZE,"
if debug ≥ 5 then log "SearchString is " & SearchString

set SearchString to alterString(SearchString, "BTS", "bts")

if debug ≥ 5 then log "SearchString is " & SearchString

-- remove string
set SearchString to alterString(SearchString, "SNAP/", "")

if debug ≥ 5 then log "SearchString is " & SearchString

-- ------------------------------------------------------
(*
alterString
  thisText is the input string to change
  delim is what string to change.  It doesn't have to be a single character.
  replacement is the new string

  returns the changed string. 
*)

on alterString(thisText, delim, replacement)
	global debug
	if debug ≥ 5 then log "in ~~~ alterString ~~~"
	set resultList to {}
	set {tid, my text item delimiters} to {my text item delimiters, delim}
	try
		set resultList to every text item of thisText
		set text item delimiters to replacement
		set resultString to resultList as string
		set my text item delimiters to tid
	on error
		set my text item delimiters to tid
	end try
	return resultString
end alterString

Jul 2, 2019 4:13 AM in response to skillet

Alot of documents that get marked up? What application(s) do you use to open these documents, and the document format, to perform that markup?


It is one thing to remove words from plain text documents, and another entirely to control unspecified application(s) and document format(s) using AppleScript, where it is possible there is no underlying AppleScript Dictionary support.


More specific requirement details are necessary before any code materializes.

Jul 4, 2019 4:00 PM in response to skillet

AppleScript alone cannot get the selected text from Scrivener because that application has no AppleScript dictionary support. I prototyped against your original text as an AppleScript text variable to get the code ready for Automator.


As you may observe, Automator passes the selected Rich Text from any application into the Automator Quick Action's Run AppleScript action, and has the provision to replace that document text with the return text from that action. It also preserves the original paragraph style, font-face, and line height too.


One of the things you might add as a comment prior to the property statements is the following:


-- Reference: https://discussions.apple.com/thread/250457121


which is the address of your main post for future reference.

Jul 2, 2019 8:34 AM in response to VikingOSX

Good to know and sorry for the lack of detail. I primarily will use it with selected text in Scrivener 3 but had hoped to also use it with selected text in MS Word and Apple Mail but that is not as vital. It could be copied and made as plain text in the clipboard and then repasted with the removed text if that makes things any easier. There will never be any images or anything like that I would need to worry about.


Here is some text and the stuff I would keep (1-DT) with the stuff in parenthesis  being things I would remove (2-TE) and keep this but remove (3-FE) (4-IN) (5-IF) (6-CR) so all the stuff in red would be gone plus the space after the closing parenthesis, so in the end to look like this. 


Here is some text and the stuff I would keep with the stuff in parenthesis being things I would remove and keep this but remove so all the stuff in red would be gone plus the space after the closing parenthesis, so in the end to look like this. 


Jul 3, 2019 10:11 AM in response to VikingOSX

Addendum:

I can remove the red codes from your text using a custom Quick Action with Pages v8.1, and Scrivener v3.1.2. Don't have MS Word.


That would be cool since it is always red for me when I do this. I could update new codes as well and that way it would always work. Scrivener is what I primarily use anyway so no need for word. I could just put it in Scrivener 3.1.2 if I ever needed to copy and paste into MS Word.

Jul 3, 2019 3:17 PM in response to VikingOSX

That is awesome it works wonderfully on 10.13.6 (High Sierra) and Scrivener is on 3.1.3, I tried it in Pages 8.1. Thank you so very much for your amazing work, I will likely use this several times per week and modify as needed, very much appreciated, I could have never done that on my own. Also your screenshots were extremely helpful!

Jul 4, 2019 3:05 PM in response to skillet

Just curious if you just ran this as AppleScript on selected text (I use Keyboard Maestro) what would you remove? I tried removing {input, parameters} from On Run and various other things but it might not be that simple. If this is not a quick simple question don't worry about it I have what I need and this is very, very helpful!

Jul 5, 2019 8:07 AM in response to VikingOSX

Alright thanks for the information and I appreciate the reminder to comment the thread. I almost always do that but have been out of doing automation for over a year now with some recent changes in my life. I have just added it to the AppleScript in the service. Thanks again for all your help with this, it is such a time saver! And by the way as you might expect it works just fine in MS Word.

This thread has been closed by the system or the community team. You may vote for any posts you find helpful, or search the Community for additional answers.

How to remove words or phrases from selected text using AppleScript

Welcome to Apple Support Community
A forum where Apple customers help each other with their products. Get started with your Apple Account.