Remove backslash from character string

I read text from a txt file and pass the contents to SQL. SQL text contains double quotes and causes problems. I would like to remove the "\" in the line below to send it to SQL

test<- "select case when \"est\" dsaf" test<- cat(test, sep="") class(test) 

returns a null UNQUOTED object

 > test<- "select case when \"est\" dsaf" > test<- cat(test, sep="") select case when "est" dsaf > class(test) [1] "NULL" 

When I pass a string without quotes in SQL, I get this error:

 Error in odbcQuery(channel, query, rows_at_time) : 'getCharCE' must be called on a CHARSXP 

and I would like it to come back using leading and trailing quotes, then I can send it to SQl and it will work.

 [1] "select case when "est" dsaf" 
+3
source share
2 answers

Perhaps you would like to see another representation of the same line:

 test2 <- 'select case when "est" dsaf' test<- "select case when \"est\" dsaf" identical(test, test2) #[1] TRUE 

When the character value is constructed with double quotes, any internal instances of \" become only double quotes. They will display print (and the REPL that you see in the interactive session) with a backslash, but using cat , you cannot determine that they are not there as a backslash.

Further evidence:

 > nchar("\"") [1] 1 

You can use either cat or print with quote=FALSE in that you want to display the value, since it really exists inside:

 > print(test, quote=FALSE) [1] select case when "est" dsaf 

This indicates that at least one version of "SQL" agrees (or "accepts") that there is no backslash when \" appears inside a line:

 > require(sqldf) Loading required package: sqldf Loading required package: gsubfn Loading required package: proto Loading required package: RSQLite Loading required package: DBI > ?sqldf > a1r <- head(warpbreaks) > a1s <- sqldf("select * from warpbreaks limit 6") Loading required package: tcltk > a2s <- sqldf("select * from CO2 where Plant like 'Qn%'") > > a2sdq <- sqldf("select * from CO2 where Plant like \"Qn%\"") > identical(a2s,a2sdq) [1] TRUE 
+9
source

The solution in R - gsub replacing backslashes worked for me.

Example:

 library(stringr) df$variable <- str_replace(df$variable,"\\\\","") df$variable before: "xyz\" df$variable after:"xyz" 
-1
source

Source: https://habr.com/ru/post/1213343/


All Articles