[R] How to create a string containing '\/' to be used with SED?

seanpor seanpor at acm.org
Wed Nov 26 09:27:13 CET 2008


Good morning,

You do not need to quote a forward slash / in R, but you do need to quote a
backslash when you're inputting it... so to get a string which actually
contains "blah\/blah"... you need to use "blah\\/blah"

http://cran.r-project.org/doc/FAQ/R-FAQ.html#Why-does-backslash-behave-strangely-inside-strings_003f

Unless this is a very very big file you shouldn't need to go out to sed, as
gsub() should work adequately... and probably quicker and cleaner.  So
something along the lines of.. (UNTESTED!!! since I don't have a
reproduceable example)

tmp1 <- readLines(configurationFile)
tmp1 <- gsub("^instance .*", paste("instance = ", data$instancePath, "/",
data$newInstance, sep = ""), tmp1)


I'm working on 50mb text files, and doing all sorts of manipulations and I
do it all inside R under windows XP...  reading a 50mb text file across the
100mb network and doing a gsub() on most lines takes an elapsed 16 seconds
on this office desktop.

hth...

Regards,
Sean


ikarus wrote:
> 
> Hi guys,
> I've been struggling to find a solution to the following issue:
> I need to change strings in .ini files that are given in input to a
> program whose output is processed by R. The strings to be changed looks
> like: 
> "instance = /home/TSPFiles/TSPLIB/berlin52.tsp" 
> 
> I normally use Sed for this kind of things. So, inside R I'd like to write
> something like:
> 
>  command <- paste("sed -i 's/^instance .*/instance = ", data$instancePath,
>                    data$newInstance, "/' ", configurationFile, sep = "")
>  system(command)
> 
> This will overwrite the line starting with "instance " using "instance =
> the_new_instance"
> In the example I gave, data$instancePath = /home/TSPFiles/TSPLIB/ and 
> data$newInstance = berlin52.tsp
> 
> The problem is that I need to pass the above path string to sed in the
> form:
> "\/home\/TSPFiles\/TSPLIB\/" 
> 
> However, I couldn't find a way to "create" such a string in R. I tried in
> several different ways,
> but it always complains saying that '\/' is an unrecognized escape!
>  
> Any suggestion? 
> 
> Thanks!
> 

-- 
View this message in context: http://www.nabble.com/How-to-create-a-string-containing-%27%5C-%27-to-be-used-with-SED--tp20694319p20696613.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list