Bash Scripting – How to Escape Every Character in Bash

bash

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?

Best Answer

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\^\!\#\&\$\(