From: Xan Xann Date: 2006-09-12T20:16:43+09:00 Subject: Re: word substitution in file Eero Saynatkari wrote: > Paul Lutus wrote: >> #!/usr/bin/ruby >> >> def substitute(source,dest,find,replace) >> data = File.read(source) >> result = data.gsub(/#{find}/,replace) >> File.open(dest,"w") { |f| f.write(result) } if data != result >> end > > The equality test there is probably unnecessary. > What you could do for a bit lower a cost, if you > really want to avoid the possible write overhead: > > # Untested too > require 'fileutils' > > def FileUtils.s(source, dest, subs = {}) > data = File.read source > search = /#{subs.keys.map {|k| Regexp.escape k}.join '|'}/ > result = data.gsub(search) {|found| subs[found]} > File.open(dest, 'w') {|f| f.write result} if $& # Regex matched > end > > FileUtils.s 'src.txt', 'dest.txt', 'foo' => 'bar' This WORKS!!!! finally Thank you very much It seems it supports regexp expressions. Is it true? Xan. -- Posted via http://www.ruby-forum.com/.