views:

214

answers:

3

I'm writing a shell script and I want to escape a string. Is there any way to convert this:

I'm happy.
You're sad.

to

I\'m happy.\nYou\'re sad.

I'm pretty sure there's some combination of sed/awk that does this....

Thanks

A: 

try

sed 's/\\ /\\n/g' | sed 's/\\'/\\\'/g'

I probably messed up a few "\" here. Best way is to try it yourself. :)

Chaitan
You don't have to run 2 sed commands, you can run multiple substitutions inside one sed invocation. I think each one is terminated with a ";" character, although if that doesn't work, then just put the 2 lines in a file and use "sed -f <filename>"
slacy
@slacy: sed -e 's/foo/bar/g' -e 's/baz/qux/g'
Charles Duffy
did not know that. thanks!
Chaitan
A: 

This works for replacing the ' with \'.

echo "I'm happy. You're sad" | sed "s/'/\\\'/g"

Are you sure you want to replace the space between "happy." and "You're" with a "\n"? \n is a newline, but your original line doesn't seem to have a new-line there.

Andy White
Yeah, he wants the \n, he just messed up his SO markup (Eddie fixed it)
derobert
A: 

I think this does what you're after. The sequencing of the operations in the sed command is quite critical. Note that this also deals with backslashes (as well as single quotes) in the string (my PS1 prompt is Osiris JL: ):

Osiris JL: cat zzz
xxx="I'm happy.
You're sad."
yyy=$(echo "$xxx" | sed 's/[\'\'']/\\&/g;s/$/\\n/;$s/\\n$//')
echo "$xxx"
echo $xxx
echo "$yyy"
echo $yyy
#eval echo $yyy
#eval echo "$yyy"
Osiris JL: sh zzz
I'm happy.
You're sad.
I'm happy. You're sad.
I\'m happy.\n
You\'re sad.
I\'m happy.\n You\'re sad.
Osiris JL:
Jonathan Leffler