Skip to content

system2 commands with backslash

4 messages · David Winsemius, Henrik Bengtsson, Zev Ross

#
Hi All,

I'm trying to edit a file in place using system2 and sed from within R. 
I can get my command to work unless there is a backslash in the command 
in which case I'm warned about an "unrecognized escape". So, for example:

system2("sed -i s/oldword/newword/g d:/junk/x/test.tex") # works fine
system2("sed -i s/oldword\s/newword/g d:/junk/x/test.tex") # does not 
work in R (the command works on the command line)

I've experimented with double slashes to escape the \s, I've tried the 
"shell" command, I've tried experimenting with shQuote and can't seem to 
get around the "unrecognized escape" issue.

By the way, it would be preferable to have a solution that avoided using 
double backslashes etc because, unfortunately, in my real-world example, 
I'm actually replacing double slashes and would prefer not to have 
quadruple slashes etc.

I'm using Windows 7, 64 bit.

Zev
1 day later
#
On Oct 10, 2013, at 8:16 AM, Zev Ross wrote:

            
Wouldn't you want to double the backslashes instead?
David Winsemius
Alameda, CA, USA
#
system2("sed", args=c("-i", "s/oldword\\s/newword/g", "d:/junk/x/test.tex"))

/Henrik
On Fri, Oct 11, 2013 at 8:58 AM, David Winsemius <dwinsemius at comcast.net> wrote:
#
Thanks to Henrik and David for responses. Both were right. A small edit 
to my description of the problem (which has now been solved). I said 
that the first version of system2 ( system2("sed -i s/oldword/newword/g 
d:/junk/x/test.tex")) worked fine but in fact it was not working, it 
just wasn't giving me an error.

Both of these work:

system("sed -i 's/oldword\\s/oldword/g' d:/junk/x/test.tex")
system2("sed", args=c("-i", "s/oldword\\s/newword/g", 
"d:/junk/x/test.tex"))

Thanks again,

Zev
On 10/11/2013 1:24 PM, Henrik Bengtsson wrote: