You should find markers or landmarks in the file that you use to turn on your gsub
processing, and then turn it off again. Using File.foreach
makes it easy to read the file line-by-line, which is very fast, and provides the granularity needed to do what you want. (See "Why is "slurping" a file not a good practice?" for reasons why "slurping" using read
or deadlines
should usually be avoided.)
Ruby has the ..
operator (AKA "flip-flop) which is designed for this purpose, and makes it very easy to process only certain chunks of something you are enumerating. See "Why does a Flip-Flop operator include the second condition?" and "Ruby - Get file contents with in a separator in an array" for ideas on how to use it.
The basic idea is to read the file line by line, looking for your block markers, and toggle processing. Something like this untested code is a general outline for it:
File.open('/path/to/some/new_file.txt', 'w') do |fo|
File.foreach('/path/to/some/file.txt') do |li|
if (li[/some_start_pattern/] .. li[/some_stop_pattern/])
li.gsub!(/pattern_of_thing_to_change/, 'text to substitute')
end
fo.puts li
end
end
By doing it this way, you can easily expand the number of blocks you're processing in a file, or the things you're replacing.
Back to ..
AKA "flip-flop". It's an operator borrowed from Perl, which got it from AWK. It remembers the state of the first test, to the left of the ..
, and when that switches to true, ..
remembers that, and returns true until the second test returns true, at which point ..
begins to returning false again. Once you get the hang of it it's amazing how fast you can grab chunks of files to process.