Piotr K
Piotr K

Reputation: 1035

Removing \" from string with cat()

I can't understand why #3 doesn't give me xxx"yyy.

xxx\\\"yyy" %>% cat() results in xxx\"yyy which is input of #2. I would expect that the second cat() in #3 would give the same result as running #2.

library(tidyverse)

#1
"xxx\"yyy"
#> [1] "xxx\"yyy"

#2
"xxx\"yyy" %>% cat()
#> xxx"yyy

#3
"xxx\\\"yyy" %>% cat() %>% cat()
#> xxx\"yyy

Created on 2021-03-02 by the reprex package (v0.3.0)

I got stuck with that when loading a text file with readr's read_file() which converts \"\", \"SQL\" in file to \\\"\\\", \\\"SQL\\\" in string.

I would like to get string with "", "SQL".

Upvotes: 0

Views: 199

Answers (2)

Konrad Rudolph
Konrad Rudolph

Reputation: 545686

I can't understand why #3 doesn't give me xxx"yyy.

In a nutshell, because … %>% cat() %>% cat() makes no sense. cat() has no return value. It writes the result to a file (which might be an output stream).

So there’s no value to be piped into the second cat() invocation argument list. Remember that a %>% b() is just a different way of writing b(a). You’re executing cat(cat(…)).

If you want to unescape a string, don’t use cat(). Use sub() or str_replace() from ‘stringr’. Though if you’re depending on ‘stringr’ anyway you might find it more convenient to use the function stringi::stri_unescape_unicode, which does exactly that, and ‘stringi’ is imported by ‘stringr’ anyway (so it’s not an additional dependency).

Upvotes: 3

akrun
akrun

Reputation: 887291

We can use

cat('xxx"yyy', '\n')
 #xxx"yyy 

Or pass it as an r' string literally without the need to escape anything

r"{xxx"yyy"}" %>%
    cat
#xxx"yyy"

Upvotes: 1

Related Questions