Skip to content

Manipulate single line in textfile

3 messages · Guillaume Filteau, Barry Rowlingson, jim holtman

#
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:
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: