From: William James Date: 2007-08-23T05:01:45+09:00 Subject: Re: Using external text file to do search and replace? On Aug 22, 6:55 am, Dan George wrote: > I recently started to take an interest in Ruby programming and with > the help of some people and by reading Learn to program by Chris Pine > I made myself a little program that has come to a halt because I don't > know if or how I can use an external file where I store the strings I > want to search and replace in text type files. > > This is what I have so far: > > txt_files = Dir.glob('**/*.txt').each do |path| > puts path > txts = path.to_s > file = File.open(txts).readlines.each { |line| > if line.match(/PROMOS:/) > then line.gsub!(/PROMO1=[A-Za-z0-9]+/, 'PROMO1=some_text') > end } > file2=File.open(txts, "w") > file2.write( file ) > end > > What I want is to be able to use an external file where I store the > values I want to search and replace with "line.gsub!" eg.: "/PROMOn=[A- > Za-z0-9]+/, 'PROMOn=some_other_text'". > I will need to use RubyScript2Exe because I'm not sure that on some > other machines I will have ruby installed and it's easier to just put > the strings I want to search and replace in an external file that is > located in the same folder as the script or on a predefined path. > > Any ideas, hints, improvements and critiques are highly welcome. # First line of file is regular expression; second is # substitution. temp = IO.readlines( "substitute" ).map{|s| s.chomp } reg_exp = Regexp.new( temp[0] ) new_text = temp[1] Dir[ "**/*.txt" ].each{|path| p path changed = false lines = IO.readlines( path ).map{|s| if s =~ /PROMOS:/ old_s = s.dup s.gsub!( reg_exp, new_text ) changed = true if s != old_s end s } # Don't write to file unless there was a change. if changed File.open( path, "w" ){|f| f.puts lines } puts " ---> changed" end }