Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 511
  • Last Modified:

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.read file
    File.open(file, 'w+'){|f| f << text.gsub(regex_to_find,text_to_put_in_place)}

  puts "Start #{Time.now}"
  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
Andrew Doades
Andrew Doades
  • 2
1 Solution
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.
Terry WoodsIT GuruCommented:
Confirmed via http://rubular.com/ that my pattern works... hope that solves your problem!
Andrew DoadesIT TechnicianAuthor Commented:
Thank You! Tested and confirmed as working!


Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now