I skip the verification check that you see to see if the line exists and something like this usually goes (here I want to replace "FOO" with "BAR"):
full_path_to_read = File.expand_path('~/test1.txt') full_path_to_write = File.expand_path('~/test2.txt') File.open(full_path_to_read) do |source_file| contents = source_file.read contents.gsub!(/FOO/, 'BAR') File.open(full_path_to_write, "w+") { |f| f.write(contents) } end
Using expand_path also probably a bit pedantic here, but I like it so that I don't accidentally drop some file I didn't want.
source share