3

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.
1
  • Please show us examples of your input and the expected output.
    – Sven
    May 16 '17 at 10:18
8

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.

1
  • 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
0

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
1
  • 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.