Ruby - Open file, find and replace multiple lines

You're replacing from the original "text" each time, the second line needs to replace the replace:

replace = replace.gsub(/bbb/, "Replace bbb with 222")

Change the third line to

replace = replace.gsub(/bbb/, "Replace bbb with 222")

An interesting wrinkle to this is if you don't want to rescan the data, use the block form of gsub:

replace = text.gsub(/(aaa|bbb)/) do |match|
  case match
    when 'aaa': 'Replaced aaa with 111'
    when 'bbb': 'Replace bbb with 222'
  end
end

This may not be the most efficient way to do things, but it's a different way to look at the problem. Worth benchmarking both ways if performance matters to you.


Here is a one liner

IO.write(filepath, File.open(filepath) {|f| f.read.gsub(/aaa|bbb/) {|m| (m.eql? 'aaa') '111' : '222'}})

IO.write truncates the given file by default, so if you read the text first, perform the regex String.gsub and return the resulting string using File.open in block mode, it will replace the file's content. Nifty right?

It works just as well multi-line:

IO.write(filepath, File.open(filepath) do |f|
    f.read.gsub(/aaa|bbb/) do |m|
      (m.eql? 'aaa') '111' : '222'
    end
  end
)

Tags:

Ruby