From: Rob Biedenharn Date: 2008-06-19T08:37:50+09:00 Subject: Re: Add new text to files On Jun 18, 2008, at 7:29 PM, Simon Blanco wrote: > Chris Conley wrote: >> Hello, >> >> I'm trying to insert new text into the middle of a file with the >> following: >> >> file = File.open("file.rb", "r+") >> file.each { |line| >> if line.match(/line text/) >> file.puts("hello") >> end >> } >> >> This works fine except that it overwrites the existing 5 characters >> to >> replace with "hello". Is there a way to insert a new line with new >> text without overwriting any existing data? >> >> Thanks! >> Chris > > try changing: > file = File.open("file.rb", "r+") > > for: > file = File.open("file.rb", "a+") > > that should do it! Uh, no, that would just cause the writes to go the end of the file. You have to open up space in the file to do this. The easiest way is to copy lines from the original file and put the possibly altered lines into a new file. If you want, you can rename the files when you're done (and delete the original). You might also want to look at the ruby command line flag '-i' and see if that gives you some ideas. -Rob Rob Biedenharn http://agileconsultingllc.com Rob@AgileConsultingLLC.com