Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find and replace in a file in Ruby

Tags:

file

replace

ruby

I have this little program I write in ruby. I found a nice piece of code here, on SO, to find and replace something in a file, but it doesn't seems to work. Here's the code:

#!/usr/bin/env ruby

DOC = "test.txt"
FIND = /,,^M/
SEP = "\n"

#make substitution
File.read(DOC).gsub(FIND, SEP)

#Check if the line already exist
unique_lines = File.readlines(DOC).uniq

#Save the result in a new file
File.open('test2.txt', 'w') { |f| f.puts(unique_lines) }

Thanks everybody !

like image 539
Simon Avatar asked Aug 02 '11 16:08

Simon


People also ask

How do I replace in Ruby?

Ruby | Set replace() functionThe replace() is an inbuilt method in Ruby which replaces the contents of the set with the contents of the given enumerable object and returns self.

How do I replace in Ruby on Rails?

The simplest way to replace a string in Ruby is to use the substring replacement. We can specify the string to replace inside a pair of square brackets and set the replace value: For example: msg = "Programming in Ruby is fun!"


1 Answers

I skip the check you make to see if the line already exists and usually go with something like this (here I want to replace 'FOO' with 'BAR'):

full_path_to_read = File.expand_path('~/test1.txt')
full_path_to_write = File.expand_path('~/test2.txt')

File.open(full_path_to_read) do |source_file|
  contents = source_file.read
  contents.gsub!(/FOO/, 'BAR')
  File.open(full_path_to_write, "w+") { |f| f.write(contents) }
end

The use of expand_path is also probably a bit pedantic here, but I like it just so that I don't accidentally clobber some file I didn't mean to.

like image 183
Chris Bunch Avatar answered Nov 11 '22 16:11

Chris Bunch