From: Robert Klemme Date: 2009-04-30T18:07:35+09:00 Subject: Re: Read and re-write file with one open? 2009/4/30 Gregory Brown : > 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. A variant exploiting Ruby's command line parameters: 11:05:08 Temp$ ruby -e '10.times {|i| puts i}' >| x 11:05:22 Temp$ cat x 0 1 2 3 4 5 6 7 8 9 11:05:23 Temp$ ./x.rb x 11:05:29 Temp$ cat x <<<0>>> <<<1>>> <<<2>>> <<<3>>> <<<4>>> <<<5>>> <<<6>>> <<<7>>> <<<8>>> <<<9>>> 11:05:34 Temp$ cat x.bak 0 1 2 3 4 5 6 7 8 9 11:05:37 Temp$ cat x.rb #!/opt/bin/ruby19 -pi.bak $_.sub! /^/, '<<<' $_.sub! /$/, '>>>' 11:05:40 Temp$ Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/