I'd like to create a service that puts any text I select in TextEdit or web page text editors into quotation marks. I understand Automator is the tool to use, but how do I create this action using AppleScript or another scripting language in OS X (Lion)?
1 Answer
One way is to create a service that runs a shell command.
For this, open Automator, create a new Service, check "Output replaces selected text", then add the action "Run Shell Script". In the box where you enter the Shell script write:
cat | sed 's/^/"/' | sed 's/$/"/' | sed 's/""//'
This takes the text you entered as input, and adds a quotation mark at the beginning and end.
Now, once you save your service, you can, for example, go to TextEdit, select the text you want to quote, then go to Services -> "name of your service", and your text should now be quoted!
Edit: I included the removal of trailing double quotation marks
-
Thank you very much! This works, but with an unwanted side effect: When I select a whole paragraph by tripple-clicking and then apply the service, an additional set of empty quotation marks is added in a new line. I suspect this has to do with the linefeed that end the paragraph, because it doesn't happen when I select text 'manually' leaving out the LF / paragraph break at the end. How might this be corrected in the script? Mar 5, 2016 at 7:50
-
1A simple workaround is to use:
cat | sed 's/^/"/' | sed 's/$/"/' | sed 's/""//'
This will remove any double quotation marks ("") that might be there. Mar 5, 2016 at 22:08 -
1Thanks again. Now I also created a keyboard shortcut for this service in System Preferences > Keyboard. Mar 6, 2016 at 7:43
-
I modified my answer to include the removal of the trailing quotation marks Mar 9, 2016 at 15:14
-
2That's nice, but I can't help pointing out that the shell script can be shortened to this:
sed -E 's/^(.+)$/"\1"/'
(on a single line). Mar 30, 2018 at 19:30