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
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
try
sed 's/\\ /\\n/g' | sed 's/\\'/\\\'/g'
I probably messed up a few "\" here. Best way is to try it yourself. :)
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.
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: