Search code examples
rsystemcat

Is there an R equivalent of other languages triple quotes?


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.


Solution

  • 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