R: How to replace space ('') in a string using * single * backslash and space ('\')

I searched many times and did not find the answer here or anywhere else. I want to replace each space ' 'with variables containing file names with '\ '. (A use case may be for shell commands, and spaces are escaped, so each file name does not appear as an argument list.) I looked at the StackOverflow question “How to replace a single backslash in R” and find that many combinations work as advertised:

> gsub(" ", "\\\\", "a b")
[1] "a\\b"

> gsub(" ", "\\ ", "a b", fixed = TRUE)
[1] "a\\ b"

but try them with a one-time version, and R ignores it:

> gsub(" ", "\\ ", "a b")
[1] "a b"

> gsub(" ", "\ ", "a b", fixed = TRUE)
[1] "a b"

If it goes in the opposite direction - removing slashes from a string, it works for two:

> gsub("\\\\", " ", "a\\b")
[1] "a b"

> gsub("\\", " ", "a\\b", fixed = TRUE)
[1] "a b"

R :

> gsub("\\", " ", "a\\b")
Error in gsub("\\", " ", "a\\b") : 
  invalid regular expression '\', reason 'Trailing backslash'

> gsub("\", " ", "a\b", fixed = TRUE)
Error: unexpected string constant in "gsub("\", " ", ""

" " - , , . ( , perl = True .)

R :

> gsub(" ", "\\\ ", "a b")
[1] "a b"

! :

> gsub(" ", "\\\\\\\\", "a b")
[1] "a\\\\b"

( '\\\ ':

> gsub(" ", "\\\\\\ ", "a b")
[1] "a\\ b"

> gsub(" ", "\\\ ", "a b", fixed = TRUE)
[1] "a\\ b"

( 3 , .)

:

  • ' ' '\ '?
  • , ?

- , , R regex.

+7
2

, :

> gsub(" ", "\\\ ", "a b", fixed = TRUE)
[1] "a\\ b"

.

, , R , .

, , :

f <- file("C:\\output.txt")
writeLines(gsub(" ", "\\", "a b", fixed = TRUE), f)
close(f)

output.txt :

a\b
+9

! ( Googling ).

( ) - print cat.

z <- gsub(" ", "\\", "a b", fixed = TRUE)

> print(z)
[1] "a\\ b"

> cat(z)
a\ b

, cat print , gsub , , .

0

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


All Articles