I am trying to build a linux sendemail command in R using paste from a bunch of values from a contact form. The message portion will have single and/or double quotes in it. Based on this post (How to escape double quote inside a double quote?) I have determined that I need to finish already opened one ('), placing escaped one (\'), then opening another one (').
For example, this works when run directly from linux command line (when using actual email addresses):
sendemail -f [email protected] -t [email protected] -u 'Subject here' -m 'My message'\''s text has single quote or maybe "double quotes".' -s smtp.gmail.com:587 -o tls=yes -xu [email protected] -xp xxxxxx
The message portion is coming from a contact form and I want to email that message to our team. I've tried using gsub to replace a single quote with '\'' so sendemail will send the message successfully but I have not found the correct gsub syntax. I've tried various gyrations of this type of thing:
gsub("'", "'\''", message)
gsub("\'", "'\\''", message)
and so on... I've tried using fixed, perl, etc. I cannot seem to get the needed syntax.
I get either no backslashes or 2 backslashes and sendemail wants only one backslash.
Certainly, I can just remove the single and double quotes from the message and it will work. I would prefer to preserve the message "as is" if possible, though.
Is this even possible with gsub and paste?
Here is a code snippet of what I'm doing:
message = gsub("\'", "\\\'", input$mailAndStoreModalText)
message = gsub("\"", "\\\"", message)
print( message)
If my input is - This's the "best" music - the gsubs above just result in the same exact thing with 0 backslashes. Then this fails:
team.email = paste0("sendemail -f ", user.email,
" -t ", distr.list,
" -u 'Contact Form Submitted' -m",
" 'Priority: ", priority," ", message,
"' -s smtp.gmail.com:587 -o tls=yes -xu [email protected] -xp xxxxx")
t <- try(system(team.email, intern = TRUE))
If you chain the gsub
s, you should pass message
variable the second time. However, you may use it like this:
message <- gsub("\"", "\\\"", gsub("\'", "\\\'", input$mailAndStoreModalText, fixed=TRUE), fixed=TRUE)
Or a regex based replacement:
message <- gsub("([\"'])", "\\\\\\1", input$mailAndStoreModalText)
Both will output This\'s the \"best\" music
as output.
See the R demo online. Note that cat(message, "\n")
command shows you the literal string that message
holds, not the string literal that you get when trying to just print message
.
Also, the ([\"'])
regex matches and captures into Group 1 either a "
or '
and the "\\\\\\1"
replacement pattern replaces the whole match with \
(that is defined with 4 backslashes) and then the value inside Group 1 (\\1
).