"foo\ bar...">

Replacing a space with a single backslash

I want to replace the white space with ONE backslash and a space like this:

"foo bar" --> "foo\ bar"

I found how to replace multiple backslashes , but could not adapt it to one backslash.

I have tried this so far:

x <- "foo bar" 
gsub(" ", "\\ ", x)
# [1] "foo bar"

gsub(" ", "\\\ ", x)
# [1] "foo bar"

gsub(" ", "\\\\ ", x)
# [1] "foo\\ bar"

However, all the results do not satisfy my needs. I need a replacement to dynamically create file paths that contain folders with type names

/some/path/foo bar/foobar.txt.

To use them for shell commands in system(), white spaces must be completed with \to

/some/path/foo\ bar/foobar.txt.

Do you know how to solve this problem?

+3
source share
2 answers

- . R, ( , print("y\n"). cat() , .

x <- "foo bar"
y <- gsub(" ", "\\\\ ", x)
print(y)
## [1] "foo\\ bar"
cat(y,"\n")  ## string followed by a newline
## foo\ bar

8 ; 6 , .

nchar(y)  ## 8

\n ( ).

z <- gsub(" ", "\n ", x)
print(z)
## [1] "foo\n bar"
cat(z,"\n")
## foo
##  bar 
nchar(z)  ## 8

, - R ( Windows). file.path(). ( , , .)

+5

, , gsub(" ", "\\ ", x) fixed=TRUE:

> x <- "foo bar" 
> res <- gsub(" ", "\\ ", x, fixed=TRUE)
> cat(res, "\n")
foo\ bar 

- R

cat "", .

+4

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


All Articles