I want to take a string like this:

Example string 59^!#&$(

And turn it into this:

\E\x\a\m\p\l\e\ \s\t\r\i\n\g\ \5\9\^\!\#\&\$\(

I've tried:

sed -e 's/./\\&/g; 1{$s/^$/""/}; 1!s/^/"/; $!s/$/"/'

as noted here:

But as noted by dalelane in a comment, this does not work under vanilla installation of bash in macOS. I have confirmed this with macOS High Sierra.

Any suggestions?

  • Did you consider Charles Duffy's first comment to that question? How are you planning to use the escaped string? In the shell, you want to use double quotes instead of inserting backslashes. Jun 28, 2019 at 18:26
  • Safest way to cd somewhere, cp a file, tee -a to a file. I'm taking into account writing/reading/navigating to/from files/folders that are Unicode-happy (Arabic characters, Japanese, Latin, Inuktitut, etc.) and include bash special characters. IMHO it's safer to just escape everything. Jun 28, 2019 at 21:58
  • The safest and easiest method is to use quotes. For example s='Example string 59^!#&$('; echo "$s" -- single quotes to prevent the "$" from expanding in the assignment, and double quotes to allow variable interpolation, but prevent any other mischief. Jun 28, 2019 at 22:16
  • I also read his comments but they didn't make much sense. Keep in mind I'm somewhat of a n00b with this stuff. Jun 28, 2019 at 22:16
  • What if I run into a double quote inside the string? Jun 28, 2019 at 22:19

1 Answer 1


This works for me with bsd sed-

echo "I am a jelly donut" | sed 's/./\\&/g'
\I\ \a\m\ \a\ \j\e\l\l\y\ \d\o\n\u\t

and with your string

echo 'Example string 59^!#&$(' | sed 's/./\\&/g'
\E\x\a\m\p\l\e\ \s\t\r\i\n\g\ \5\9\^\!\#\&\$\(

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .