DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Use A Regular Expression Substitution On The Contents Of A File

  • submit to reddit
        The following code can be used to replace content inside a file. Be warned however, that it loads the contents of the file into memory.
I chose this solution because i didn't want to use a temporary file.

def replace_in_file(filename, s, r)
  lines = [], "r"){|f| lines = f.readlines }
  lines = lines.inject([]){|l, line| l << line.gsub(s, r)}, "w"){|f| f.write(lines) }