R – Escape a string

escapingscriptingshell

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

Best Solution

You can use plain Bash for that (see http://tldp.org/LDP/abs/html/string-manipulation.html).

Something like:

#!/bin/bash
X="I'm happy.
You're sad."
echo "========== BEFORE =========="
echo "${X}"
echo "========== AFTER ==========="
X="${X//\'/\\\'}"
X="${X//$'\n'/\\n}"
echo "${X}"
echo "============================"

Will produce output:

========== BEFORE ==========
I'm happy. You're sad.
========== AFTER ===========
I\'m happy.\nYou\'re sad.
============================