I'm trying to find and replacace the string "placeholder" in a text
file. Any idea how I could get the following code to work?
file = File.open('/folder/template.txt', 'r+')
file.gsub!(/placeholder/, "word")
Thanks,
The most "natural" way would be to use ruby-mmap.
http://raa.ruby-lang.org/project/mmap/
The other method would be of course:
File.open("source.txt", "r") do |src|
File.open("sink.txt", "w") do |sink|
src.each_line { |line| sink.write(line.gsub(/placeholder/, "word")) }
end
end
require 'fileutils'
FileUtils.mv("sink.txt", "source.txt")
This requires twice the space of the file while working so it may not
be viable for large files.
Incidentily ruby has a shortcut for doing this:
ruby -inp -e 'gsub!(/placeholder/, "word")' /folder/template.txt
To handle those really big files where you simply cannot afford to
have two copies simultaneously, or don;t have the address space to map
the whole file into memory with mmap, you can read in fixed sized
chunks, modify them in memory and then write them back out. It's a bit
more complicated than "fixed sized" chunks since the transformed text
may be smaller of larger than the original chunk.