Manik
Manik

Reputation: 15

Having issues searching through file and replacing

I'm having a bit of trouble searching through a file and editing certain parameters of the file. The code is below

file_names = ["#{fileNameFromUser}"]

file_names.each do |file_name|
 text = File.read(file_name)
 replacedcontent = text.gsub(/textToReplace/, "#{ReplaceWithThis}")
 replacedcontent += text.gsub(/textToReplace2/, "#{ReplaceWithThis2}")

# To write changes to the file, use:
File.open(file_name, "w") {|file| file.puts replacedcontent}
end

so right now what it does is that it print the contents of the file twice and I can only assume its because its inside the do loop. My end goal here is that the file has textToReplace and textToReplace2 and I need it to read through the file, replaced both with whatever the user inputs and save/write changes to the file.

Upvotes: 0

Views: 33

Answers (2)

Amadan
Amadan

Reputation: 198438

it print the contents of the file twice and I can only assume its because its inside the do loop

Nope, it's because you append it twice:

text = first_replacement_result
text += second_replacement_result

There's two ways to do this: one with mutation:

text.gsub!(...) # first replacement that changes `text`
text.gsub!(...) # second replacement that changes `text` again

or chained replacement:

replacedcontent = text.gsub(...).gsub(...) # two replacements one after another        

Upvotes: 2

dkulkarni
dkulkarni

Reputation: 2830

You will need to re-use replacedcontent instead of concatenating it to avoid printing it twice.

file_names = ["#{fileNameFromUser}"]

file_names.each do |file_name|
text = File.read(file_name)
replacedcontent = text.gsub(/textToReplace/, "#{ReplaceWithThis}")
replacedcontent = replacedcontent.gsub(/textToReplace2/, "#{ReplaceWithThis2}")

# To write changes to the file, use:
File.open(file_name, "w") {|file| file.puts replacedcontent}
end

OR

replacedcontent = text.gsub(/textToReplace/, "#{ReplaceWithThis}").gsub(/textToReplace2/, "#{ReplaceWithThis2}")

Upvotes: 1

Related Questions