# How can I escape double quotes in content gotten from file

I am trying to escape double quotes when adding content from statusfile.log tostatusfile_truncated.log.

I have looked around and are just getting more confused. How would you achieve it?

This is what I got so far:

#!/bin/bash

statusfile="statusfile.log"
statusfile_truncated="statusfile_truncated.log"
tail -n 50 $statusfile >>$statusfile_truncated


Content of statusfile.log:

2017-05-15 22:36:18 test.somedomain.com <--- 250 CWD successful. "/xxxxxxxxxxxxx" is current directory.
2017-05-15 22:36:18 test.somedomain.com <--- 250 CWD successful. "/xxxxxxxxxxxxx" is current directory.
2017-05-15 22:36:18 test.somedomain.com <--- 250 CWD successful. "/xxxxxxxxxxxxx" is current directory.


Content of statusfile_truncated.log should be:

2017-05-15 22:36:18 test.somedomain.com <--- 250 CWD successful. \"/xxxxxxxxxxxxx\" is current directory.
2017-05-15 22:36:18 test.somedomain.com <--- 250 CWD successful. \"/xxxxxxxxxxxxx\" is current directory.
2017-05-15 22:36:18 test.somedomain.com <--- 250 CWD successful. \"/xxxxxxxxxxxxx\" is current directory.

• Please show us examples of your input and the expected output.
– Sven
May 16 '17 at 10:18

I you just want to insert a backslash in front of the double quote you could go with sed like this:

sed 's/"/\\"/g' $statusfile >>$statusfile_truncated


But if there is to be real escaping going on there is other tools and techniques that should be considered.

• This can also be used together with tail as a pipeline: tail -n 50 $statusfile | sed 's/"/\\"/g' >>$statusfile_truncated. BTW, I agree with the note about "real escaping"; this sounds suspiciously like a partial solution to a larger problem. May 16 '17 at 18:07

The best way to quote a string in bash is to use the %b option in printf. This will handle all special chars:

$variablename='foo "bar and C:\\foo\\bar'$ printf '%b\n' "\$variablename"
foo "bar and C:\foo\bar

• bash's printf %b format escapes and/or quotes strings suitably for interpretation by bash. If the string will be interpreted by something other than bash (even a different shell), that will sometimes produce completely inappropriate output. In order to quote/escape a string properly, you need to know how it's going to be parsed, and what parsing rules it'll be subject to. May 16 '17 at 20:59