bob
bob

Reputation: 71

Remove a single backslash in paste0 output

paste0(" SqlCmd -s sqlserver2 -Q ", "\"BACKUP DATABASE [mydb] TO DISK = '","D:/temp/mydbcopy.bak' ") 

is giving output as

" SqlCmd -s sqlserver2 -Q \"BACKUP DATABASE [mydb] TO DISK = 'D:/temp/mydbcopy.bak' "

but I want the output to be without the backslash

" SqlCmd -s sqlserver2 -Q "BACKUP DATABASE [mydb] TO DISK = 'D:/temp/mydbcopy.bak' " "

Please help.

Upvotes: 1

Views: 951

Answers (1)

Konrad Rudolph
Konrad Rudolph

Reputation: 545488

Your code does the correct thing.

The backslash isn’t actually in the string, just as the surrounding quotes aren’t in the string. That’s just how R displays character strings in the terminal. To see the actual string content, use message:

x = paste0(" SqlCmd -s sqlserver2 -Q ", "\"BACKUP DATABASE [mydb] TO DISK = '","D:/temp/mydbcopy.bak' ") 
message(x)

This also shows you that your string is (probably) currently missing a closing " character.

As a general rule I strongly recommend against building command lines using raw string functions, it’s error-prone and hard to read. Use shQuote instead: this function is purpose-built to ensure correctly quoted arguments.

cmd_tokens = c("SqlCmd", "-s", "sqlserver2", "-Q", "BACKUP DATABASE [mydb] TO DISK = 'D:/temp/mydbcopy.bak'")
cmd = paste(shQuote(cmd_tokens), collapse = " ")

Here, each token of the command line (the command itself and all the arguments) are individual strings in a vector, and we apply shQuote to all of them in turn before concatenating them. Better yet, instead of concatenating the command yourself, pass the tokens as they are to the system2 command to execute it:

args = c("-s", "sqlserver2", "-Q", "BACKUP DATABASE [mydb] TO DISK = 'D:/temp/mydbcopy.bak'")

system2("SqlCmd", args)

Upvotes: 1

Related Questions