From: Gregory Brown Date: 2009-04-30T14:09:41+09:00 Subject: Re: Read and re-write file with one open? On Thu, Apr 30, 2009 at 12:27 AM, Adam Bender wrote: > I would like to write a Ruby script that opens a text file, performs a gsub > on each line, and then overwrites the file with the updated contents.  Right > now I open the file twice: once to read and once to write.  The reason for > this is that if I try to perform both operations on the same IO object by > calling io.rewind and writing from the beginning, and the substituted word > is shorter than what it is replacing, some portion of the end of the > original file remains.  Is there an idiom for "clearing" the contents of the > file before writing? Yes, but typically this is done by creating a new file and then renaming it to replace the old one. Here's an example from my upcoming book "Ruby Best Practices"[0]. It naively strips comments from source files. You can modify it to fit your needs. ---------- require "tempfile" require "fileutils" temp = Tempfile.new("without_comments") File.foreach(ARGV[0]) do |line| temp << line unless line =~ /^\s*#/ end temp.close FileUtils.cp(ARGV[0],"#{ARGV[0]}.bak") # comment out if you don't want backups. FileUtils.mv(temp.path,ARGV[0]) ---------- -greg PS: sorry for the shameless book plug, but it really might be helpful for questions like these. :) [0] http://rubybestpractices.com