From: zdennis Date: 2005-12-02T01:56:51+09:00 Subject: Re: What is the best way to edit a file to eliminate a line Steve [RubyTalk] wrote: > Mike Fletcher wrote: > >> File.new( "stuff.txt" ) do | in | >> File.new( "newstuff.txt", "w" ) do |out| >> in.each { | line | out.print line unless line =~ /foo/ } >> end >> end > > That's remarkably similar to my current rough-n-ready approach - the > one I consider inelegant...(N.B. the example above doesn't address the > problem of atomically replacing stuff.txt with newstuff.txt.) I was > thinking that something like this would be preferable: > > FileModify.open 'stuff.txt' { |mfile| mfile.delete(/foo/) } > > Of course, I've just invented FileModify off the top of my head, and I > imagine it being 'transactional' - i.e. any exception arising in the > block would prevent any change to stuff.txt. I'd prefer not to go > around re-inventing the wheel if FileModify (or something similar) > already exists. I don't need it to be desperately scalable or quick - > on the other hand, reliability _is_ a key concern and I'd prefer to use > the neatest possible syntax. > I have done some things like: def write filename, data File.open( filename, 'w' ){ |file| file.write data } end begin data = IO.read( 'stuff.txt' ) write 'stuff.txt', data.gsub( /^foo(\n|$)/, '' ) rescue write 'stuff.txt.orig', data end Zach