From: Rick DeNatale Date: 2007-06-14T02:49:51+09:00 Subject: Re: why writing the file is partial On 6/13/07, Robert Klemme wrote: > On 13.06.2007 18:58, Li Chen wrote: > > #####input file format### > > test.001 > > xxx\2.000000\$P1G\2.000000\xxx > > xxx\2.000000\$P1G\2.000000\xxx > > xxx\2.000000\$P1G\2.000000\xxx > > xxx\2.000000\$P1G\2.000000\xxx > > > > > > ### the updated file### > > test.001 > > xxx\2.000000\$P1G\2.000000\xxx > > xxx\1.000000\$P1G\1.000000\xxx > > xxx\2.000000\$P1G\2.000000\xxx > > xxx\1.000000\$P1G\1.000000\xxx > Reading and writing one file at the time is a dangerous thing to do - > especially if pattern and replacement can have different lengths. If > you want to do it properly, then you need to #seek before you switch > from reading to writing and back AFAIK. Right, I think what's happening here is that he reads the first line, the file cursor is positioned after the first line, so he overwrites the SECOND line with the updated first line, and is now positioned at the end of the second line, etc. etc. He needs to seek back to the beginning of the line before he writes: file.each_line do |line| if pat.match(line) line.gsub!(pat,sub) #replace the line in place file.seek(-line.length, IO::SEEK_CUR) file.print line #write/update the file end end end But this will only work in the case where the replacement is the same length at the original, if you you're either going to leave stuff behind, or will overwrite the next line. In either case you're more likely to end up with gibberish than something you like. > But I'd use a temporary file, > this is much safer. Amen, and it will preserve the original file "just in case" you have to debug the program. -- Rick DeNatale My blog on Ruby http://talklikeaduck.denhaven2.com/