From: Dan George Date: 2007-09-07T07:05:07+09:00 Subject: Re: Using external text file to do search and replace? On Sep 6, 8:06 pm, Stefano Crocco wrote: > Alle gioved� 6 settembre 2007, Dan George ha scritto: > > > > > I tried what you said and it shows it works and I get an Exit code: 0 > > but nothing is modified. > > > Here's what I have now: > > > require 'yaml' > > promo = File.open('promo.yaml') > > yp = YAML::load_documents(promo) do |item| > > txt_files = Dir.glob('**/*.txt').each do |path| > > puts path > > file = File.open(path).readlines.each { |line| > > if line.match(/PROMOS/) > > then line.gsub!(item['search'], item['sub']) > > end } > > File.open(path, 'w'){|f| f.write file} > > end > > end > > > And my YAML file looks like this: > > > --- > > search: /PROMO1=[A-Za-z0-9]+/ > > sub: PROMO1=some_text > > > Can anyone please tell me what's wrong with it? > > The reason your code doesn't work is that the search string is stored in the > YAML file as a string, not as a regexp. To use it as a regexp, you need to > create a regexp from it: remove the delimiting / in the regexp in the YAML > file and replace the call to gsub! with: > > gsub(Regexp.new(item['search']), item['sub']) > > and it should work. > > Without creating the regexp, gsub! would look for a > literal '/PROMO1=[A-Za-z0-9]+/' in the argument, not for a Regexp. (As I > wrote in my previous post, you can store directly a in the YAML file: > > search: !ruby/regexp /PROMO1=[A-Za-z0-9]+/ > ). > > By the way, you don't need to store the return value of YAML::load_documents > in a variable. > > I hope this helps > > Stefano Thanks a lot for your help Stefano! It works great! Cheers :)