From: Chris Conley Date: 2008-06-20T05:12:00+09:00 Subject: Re: Add new text to files ------=_Part_6513_23719738.1213906398583 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit Content-Disposition: inline Hi all, thanks for the info! I ended up finding this solution from digging through some Rails generators: def gsub_file(path, regexp, *args, &block) content = File.read(path).gsub(regexp, *args, &block) File.open(path, 'wb') { |file| file.write(content) } end line = 'Rails::Initializer.run do |config|' gsub_file 'config/environment.rb', /(#{Regexp.escape(line)})/mi do |match| "#{match}\n hello\n" end It basically reads the file, finds and replaces the line with itself and whatever you want to add in to 'content'. Then writes back to the file. On Thu, Jun 19, 2008 at 2:43 PM, Bryan JJ Buckley wrote: > Hi, > To edit a file in place, you could try something like > > File.open('file.rb', 'r+') do |file| > file.each do |line| > if line =~ /line text/ > file.seek(-line.size, IO::SEEK_CUR) > file.puts("Hello") > end > end > end > > Note the minus before line.size. This will probably fall over on > non-ascii files, as you're seeking back too little (String#size > returns the number of letters). > > However, this is a C-ish approach, and unless you want your programme > to run on a tamagotchi, or something, you're probably better off just > reading in one file, and writing to another. > > > > 2008/6/19 Chris Conley : > > 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 > > > > > > > > -- > JJ > > -- Chris Conley 484.467.7873 @chrisconley ------=_Part_6513_23719738.1213906398583--