Over a million developers have joined DZone.

Use A Regular Expression Substitution On The Contents Of A File

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 = []
  File.open(filename, "r"){|f| lines = f.readlines }
  lines = lines.inject([]){|l, line| l << line.gsub(s, r)}
  File.open(filename, "w"){|f| f.write(lines) }

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}