Service to remove all white space from a string

applescriptterminal

I'm ultimately looking to create a service that will allow me to count all selected non-whitespace characters. To get there though, I'm looking for a way to remove all whitespace characters from a string in a service that I can then use for other such purposes. For example, I mainly want to use it to get quick DNA coordinates while looking at output in Terminal.app, but I can think of other uses, like counting code characters.

I have found applescripts to remove spaces, but nothing I've found appears to account for tabs, newline characters, carriage returns, or any other strange or weird character that doesn't display.

Note: I don't want to create a file or use or change the clipboard.

Side-question: Is there a way to display the result (briefly) in a bezel, like the way you can display phone numbers from the Contacts app?

Best Answer

In Automator, create a new Service with the following settings:

  • Service receives selected [text] in [Terminal]

Add a Run AppleScript actions, replacing the default code with the code below:

Example AppleScript code:

on run {input, parameters}

    set selText to item 1 of input as text
    set AppleScript's text item delimiters to {space, tab, linefeed, return}
    set selText to text items of selText
    set AppleScript's text item delimiters to {}
    set selText to selText as string

    display dialog ¬
        "The selection contains " & (count characters of selText) ¬
        & " characters." & linefeed & linefeed & selText ¬
        buttons {"OK"} default button 1

end run

Save the Automator Service as, e.g.: Count Selected Characters

Now in Terminal, select the wanted selection, e.g:

Selected Text

Right-click and select Count Selected Characters from the Services context menu.

Example output of the selection show above:

Display Dialog


Note: The example AppleScript code is just that and does not employ any error handling and is meant only to show one of many ways accomplish a task. The onus is always upon the User to add/use appropriate error handling as needed/wanted.