Dane O'Connor Dane O'Connor - 3 months ago 13
Ruby Question

Ruby: Search file text for a pattern and replace it with a given value?

Learning Ruby. I'm looking for a script to search a file (or list of files) for a pattern and, if found, replace that pattern with a given value.

Thoughts?

Answer

Here's a quick short way to do it.

file_names = ['foo.txt', 'bar.txt']

file_names.each do |file_name|
  text = File.read(file_name)
  new_contents = text.gsub(/search_regexp/, "replacement string")

  # To merely print the contents of the file, use:
  puts new_contents

  # To write changes to the file, use:
  File.open(file_name, "w") {|file| file.puts new_contents }
end