tags:

views:

168

answers:

3

I need a bash command that will convert a string to something that is escaped. Here's an example:

echo "hello\world"|escape|someprog

Where the escape command makes "hello\world" into "hello\\world". Then, someprog can use "hello\world" as it expects. Of course, this is a simplified example of what I will really be doing.

+1  A: 

You can use perl to replace various characters, for example:

$ echo "Hello\ world" | perl -pe 's/\\/\\\\/g'
Hello\\ world

Depending on the nature of your escape, you can chain multiple calls to escape the proper characters.

Michael Aaron Safyan
Why not sed? $echo "hello\ world" |sed 's/\\/\\\\/'
Space
@Octopus, that is also a valid option. I happen to be more comfortable with perl, but yeah, that works, too.
Michael Aaron Safyan
A: 

Pure Bash, use parameter substitution:

string="Hello\ world"
echo ${string//\\/\\\\} | someprog
fgm
+2  A: 

In Bash:

printf "%q" "hello\world" | someprog

for example:

$ printf "%q" "hello\world"
hello\\world
Dennis Williamson