I want to replace a white space with ONE backslash and a whitespace like this:
"foo bar" --> "foo\ bar"
I found how to replace with multiple backslashes but wasn't able to adapt it to a single backslash.
I 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 outcomes do not satisfy my needs. I need the replacement to dynamically create file paths which contain folders with names like
/some/path/foo bar/foobar.txt
.
To use them for shell commands in system()
white spaces have to be exited with a \
to
/some/path/foo\ bar/foobar.txt
.
Do you know how to solve this one?
Your problem is a confusion between the content of a string and its representation. When you print out a string in the ordinary way in R you will never see a single backslash (unless it's denoting a special character, e.g. print("y\n")
. If you use cat()
instead, you'll see only a single backslash.
x <- "foo bar"
y <- gsub(" ", "\\\\ ", x)
print(y)
## [1] "foo\\ bar"
cat(y,"\n") ## string followed by a newline
## foo\ bar
There are 8 characters in the string; 6 letters, one space, and the backslash.
nchar(y) ## 8
For comparison, consider \n
(newline character).
z <- gsub(" ", "\n ", x)
print(z)
## [1] "foo\n bar"
cat(z,"\n")
## foo
## bar
nchar(z) ## 8
If you're constructing file paths, it might be easier to use forward slashes instead - forward slashes work as file separators in R on all operating systems (even Windows). Or check out file.path()
. (Without knowing exactly what you're trying to do, I can't say more.)
To replace a space with one backslash and a space, you do not even need to use regular expression, use your gsub(" ", "\\ ", x)
first attempt with fixed=TRUE
:
> x <- "foo bar"
> res <- gsub(" ", "\\ ", x, fixed=TRUE)
> cat(res, "\n")
foo\ bar
See an online R demo
The cat
function displays the "real", literal backslashes.