0

I want to echo a variable with spaces into a text file.

a=a\ b\ c
echo $a > /tmp/a

The above results in a file with a b c in it. What if I need the file to read a\ b\ c?

I've tried printf %q $a but that doesn't seem to do what I want either.

Note: Also assume that I don't produce the content of $a it is passed to me outside my control. I just need to make sure it is saved with escaped spaces.

3 Answers 3

3

Backslashes escape the next character; in your case, you've escaped the space, at which point the contents of $a become: a b c. If you want the contents of $a to have backslashes, then you need to escape them:

a=a\\\ b\\\ c

or

a='a\ b\ c'

If $a already contains text with spaces and you want to save it to a file, simply:

printf "%q" "$a" > /tmp/a

When you ran:

printf "%q" $a > /tmp/a

You told printf to quote 3 split & globbed pieces of text: a, b, and c, which it dutifully escaped (doing nothing) before being redirected into /tmp/a as abc.

Take a good read through: Why does my shell script choke on whitespace or other special characters? to see what's going on.

2
  • What if I want to convert a variable where spaces aren't escaped to one where they are? For example $a is simply random text but it needs to be saved with escaped spaces? Should I run grep and replace spaces with \ ? Commented Nov 21, 2017 at 16:03
  • Maybe something like echo $a | tr ' ' '\ ' > /tmp/a? Commented Nov 21, 2017 at 16:12
1

Just put it in quotes.

a="a\ b\ c"

Alternatively, escape the escape.

a=a\\\ b\\\ c

Both end up with the same result.

2
  • Thanks but my question is about how to print the output. I don't actually have control of setting the contents of $a in my situation. I just need to print it out with escaped spaces. Commented Nov 21, 2017 at 16:06
  • How does it come in? Commented Nov 21, 2017 at 16:07
1

Solution based on feedback from Jeff:

echo $a | sed -e "s/ /\\\ /g" > /tmp/a
1
  • You should really quote $a
    – Jeff Schaller
    Commented Nov 21, 2017 at 17:47

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .