From: Ghislain Mary Date: 2005-04-19T18:32:23+09:00 Subject: Re: Modifying content in a file Robert Klemme a 辿crit : > You can do that easier: > > to_file.puts( /^caption:/ =~ line ? caption : line ) > In fact, I am doing several substitution, but I forgot to tell it. > > Depends on your file's sizes. If they are moderately sized you can slurp > the whole thing in, modify contents in mem with a single gsub and then > write them in one go. > Thanks. Since the file can be quite large, I continue using something like before but with a Tempfile now. That gives something like: require 'tempfile' require 'fileutils' include FileUtils def clean_file(filename) # Define the new caption caption = "caption: my caption" # Process the content of the file begin tf = Tempfile.new(filename) File.open(filename) do |from_file| from_file.each do |line| case when line =~ /^caption:/: line.sub!($&, caption) # Other substitutions... end tf.print line end end ensure tf.close unless tf.nil? end # Replace the previous file with the new. cp(tf.path, filename) end But can't we open a file in read-write mode and directly do substitutions in it without using an auxiliary file? Ghislain