Dane O'Connor Dane O'Connor - 1 year ago 120
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.


Answer Source

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 }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download