> From owner-mac-perl@iis.ee.ethz.ch Fri Jan 19 14:04:44 1996 > X-Sender: mpeursem@pop.knoware.nl > Mime-Version: 1.0 > Content-Type> : > text/plain> ; > charset="us-ascii"> > To: ERNESTO GONZALEZ <GONZALEZ@Frodo.MGH.Harvard.EDU> > Subject: Re: [MacPerl] search and replace a specific line in a file. > Cc: mac-perl@iis.ee.ethz.ch > Sender: owner-mac-perl@iis.ee.ethz.ch > Content-Length: 1194 > X-Lines: 28 > > Ernesto Gonzalez <Gonzalez@molbio.mgh.harvard.edu> wrote: > >I am writing a CGI that searches a flat file for a line that matches a > >specified string. What I want to do when I find the line is to manipulate > >some of the contents and then write the line back to the file at the same > >line number. I am able to do everything except for the print to the file > >at the right spot (it just appends to the file). I have the Camel book > >and the Llama book and I can't seem to figure out how to print to a > >specific line in the file. I know about the "$." variable that holds the > >current input line number and that "$_" contains the input line contents, > >but how do I get "print" to print $string to OUTPUTFILE at "$." ? > > A file is one lineair string of characters in which you cannot insert or > delete. If the file is not too big, you can do the following: If you can, read the file one line at a time, and just write out to a temp file the lines you aren't modifying. If you match your conditions, modify the line and write it out. and so on. Then swap names of the original file and the temp file, or just rename the temp file to the original. On the Unix end of things, there is no record of a line number, just a byte offset into the file. ( and MacPerl follows Unix conventions) If you have the byte offsets of the beginnings of the lines, you can modify a line directly, but the changed line has to be shorter than the original ( and then padded). The "dbm" library lets you index the file, and "randomly" access the lines. It takes care of the messy details for you. Of course, if you are going to sequentially search the file to match your condition, then you might as well read / modify ( or not modify) and then write. ( but NOT TO THE ORIGINAL FILE!!! work on a copy or a temp file). This is really inelegant, but has worked for me in the past. art