Re: Replace lines in a text file?

Tech-Archive recommends: Repair Windows Errors & Optimize Windows Performance



> I am needing to read a text file, more specifically a certain line (let's
> just say line 4) of the text file, match it against a pattern using an IF
> THEN statement, and if it does not match the pattern I need to replace that
> line with a set string. I am familiar with opening and closing, read and
> writing to text files, but I cannot find a solution for line replacement.

That's because there isn't one. You can't edit files in situ.

> I also know that you cannot simultaneously write to a file while it is open
> for a read. Is there a solution to this?

The only solution to this is either to read the whole file, close it, and reopen
it for writing, or create a new file for writing.

For your particular situation, there are a couple of ways to go at it, depending
on how big the file you want to edit is. If it is small, you can load the whole
file, edit the line in question, then write it back to the file. If the file is
large, you read it one line at a time, edit the line or lines you want, and
write back to a temporary file. When you are done, delete the original and
rename the temp to the original name.
--
Crash



.



Relevant Pages

  • Re: Replace lines in a text file?
    ... This is great Bruce what if i have other characters in the way e.g. i wan to ... and if it does not match the pattern I need to replace ... >>> writing to text files, but I cannot find a solution for line replacement. ... You can't edit files in situ. ...
    (microsoft.public.windows.server.scripting)
  • Re: Editor wants to help !
    ... edit. ... you studied rasfc for some time before writing it. ...
    (rec.arts.sf.composition)
  • Re: The Idiom - monthly online contest & publication for Short Story Writers
    ... "edit" my writing, I thought I'd take a whack at yours: ... ahem. ...
    (rec.arts.sf.composition)
  • Re: Blind and Toothless: Chapter 1
    ... and most of them are no bloody good. ... Anyone who is "WAY too lazy" to edit his work isn't ... writing, he's just typing. ...
    (misc.writing)
  • Re: Extract Data With DOS
    ... but I'm not sure about how large a file you could edit... ... It'd probably be much less under DOS. ... If you have VI or a VI clone with EX/ED support, ... v - match all lines without pattern ...
    (comp.os.msdos.programmer)