Replace text in files

I've got the below code to replace text between two tags in an XML file, the script seems to open the file, and debugging code shows its finding the tags correctly, however, its not actually replacing the text (or writing back to the file)

What I'm looking to do, is replace anything between <ConnectionString> and </ConnectionString>

Can someone lend a hand please?


def ChangeOnFile(file, regex_to_find, text_to_put_in_place)
    text= file, 'w+'){|f| f << text.gsub(regex_to_find,text_to_put_in_place)}

  puts "Start #{}"
  puts "I'm in #{Dir.pwd}"
  folders = Dir.glob("**/")
  for fldr in folders
    puts "Searching #{fldr}"
    Dir.chdir("#{fldr}") do
    Dir["*.xml"].each do |tempfile|
    puts "Process File #{tempfile}"
    #build the connection string
    replace = "My New Text"
    #update the file
    ChangeOnFile(tempfile, /<ConnectionString>\d+<\/ConnectionString>/, replace)
rescue Exception => e
  puts "Error: #{e}"
end #begin
LVL 10
Andrew DoadesIT TechnicianAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Terry WoodsIT GuruCommented:
Disclaimer: I don't know anything about ruby, just regular expressions.

The pattern:
requires an integer number of at least digit between <ConnectionString> and <\/ConnectionString>

If as you say you want to replace anything between those tags, then you should be probably using pattern:

I'm assuming the ? works to make the .* non-greedy in the ruby regex engine - it doesn't work in all languages, but I'd guess it probably will in this case.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Terry WoodsIT GuruCommented:
Confirmed via that my pattern works... hope that solves your problem!
Andrew DoadesIT TechnicianAuthor Commented:
Thank You! Tested and confirmed as working!

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.