I know you can escape special characters with "\"'s, but I'm interesting in creating commands that will go to the terminal that include special characters, and these cannot read the backslashes well.
As a simplified example, I'd like to have a command that looks like:
echo hello "w" or'l'd
Which could be achieved by something like
system(command="""echo hello "w" or'l'd""")
But R doesn't handle triple quotes. Is there another way? Even catching the output from cat() would be ok. e.g. newCommand = cat("echo hello \"w\" orld")
Thanks.
The triple quotation is a nice way to be able to include other types of quotation within your string without having to use escape characters. For example: print("He said \"my name's John\"") That example requires escape characters \" to use double quote marks.
They can be used interchangeably but double quotes are preferred (and character constants are printed using double quotes), so single quotes are normally only used to delimit character constants containing double quotes.
String literals inside triple quotes, """ or ''', can span multiple lines of text. Python strings are "immutable" which means they cannot be changed after they are created (Java strings also use this immutable style).
You can escape the "
with \"
. I would also use shQuote
if your intention is to run system commands. It takes care of the relevant escaping for you...
shQuote( "hello \"w\" orld" , type = "cmd" )
#[1] "\"hello \\\"w\\\" orld\""
You should be aware that what you see on-screen in the R interpreter is not exactly what the shell will see.. e.g.
paste0( "echo " , shQuote( "hello \"w\" orld" , type = "sh") )
#[1] "echo 'hello \"w\" orld'"
system( paste0( "echo " , shQuote( "hello \"w\" orld" , type = "sh") ) )
#hello "w" orld
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With