How to search file text for a pattern and replace it with a given value

Dane O'Connor picture Dane O'Connor · Aug 13, 2009 · Viewed 123.3k times · Source

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

Max Chernyak picture Max Chernyak · Aug 13, 2009

Disclaimer: This approach is a naive illustration of Ruby's capabilities, and not a production-grade solution for replacing strings in files. It's prone to various failure scenarios, such as data loss in case of a crash, interrupt, or disk being full. This code is not fit for anything beyond a quick one-off script where all the data is backed up. For that reason, do NOT copy this code into your programs.