Find and replace in a file in Ruby

I have this little program that I write in ruby. I found a good piece of code here on SO to find and replace something in the file, but it does not seem to work. Here is 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 everyone!

+4
source share
1 answer

I skip the verification check that you see to see if the line exists and something like this usually goes (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 

Using expand_path also probably a bit pedantic here, but I like it so that I don't accidentally drop some file I didn't want.

+8
source

All Articles