Hello all, Is it possible to modify a single line in a textfile? I know it is possible to load the whole text file, do the change, and save this as a new file. However, this is not practical in my case, because the document is huge and cannot be fully loaded in R. Any idea? Best, Guillaume
On Fri, Apr 17, 2009 at 9:20 AM, Guillaume Filteau <filteau at unc.edu> wrote:> Hello all, > > Is it possible to modify a single line in a textfile? > > I know it is possible to load the whole text file, do the change, and ?save > this as a new file. However, this is not practical in my case, because the > document is huge and cannot be fully loaded in R. > > Any idea?You seek "seek"! Rough outline: Open the file as a read-write connection using con = file(fileName, open="r+") Seek to where you want to change the line using seek(con, where linelength*linenumber) Write the new text using cat("my new text",file=con) Close the connection using close(con). Note this works if the lines are all the same length, since the position used in seek() is in bytes. You might be able to scan() or readLines() up to the point you want to change and then read off the byte position with seek(con,where=NA). Note that seek keeps a read and a write position. Further complications include making sure you don't write over end-of-line characters - your replacement text has to be the same size as the existing text. read help("connection") and help("seek") for more help :) And test it on something else first, lest ye stomp on the original. And keep backups. Barry
You can also read/write portions of the text till you get to the line you want to change, change it and then continue copying the lines. This is what would be done with any other software approach in trying to replace 'text' that may not be the same length. On Fri, Apr 17, 2009 at 4:20 AM, Guillaume Filteau <filteau at unc.edu> wrote:> Hello all, > > Is it possible to modify a single line in a textfile? > > I know it is possible to load the whole text file, do the change, and ?save > this as a new file. However, this is not practical in my case, because the > document is huge and cannot be fully loaded in R. > > Any idea? > Best, > Guillaume > > ______________________________________________ > R-help at r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. >-- Jim Holtman Cincinnati, OH +1 513 646 9390 What is the problem that you are trying to solve?