Amos Shapira wrote:

Actually - if it's a one-off thing and the input is not large (or lots
of files) then it's good enough.

Otherwise if you are going to do it many times and care about performance then:

1. Do the entire read loop in perl.
2. Assign the "match" and "replace" strings into a hash.
3. Build a perl regexp: (\Qmatch1\E|\Qmatch2\E|...)
4. use it with something like s/$regexp/$hash{$1}/ge

Yup. Much more efficient. Read all the search and replace strings
once into a hash. Then perform a single pass through the target
file.

Here is a version written in ruby, which I am learning now.
Like python, ruby doesn't suffer from the "line noise" problems
inherent in perl :) [well, except for that ugly rexp in scan()]

-------------------------------------------------------------------

#!/usr/bin/env ruby -w

# two parameters are passed in, a mapping file and the text file to replace in

mappingfile, templatefile = ARGV

translate = { }
File.read(mappingfile).scan(/^([^,]*),(.*)$/) do | replace, search |
  translate[search.strip] = replace.strip
end

safesearch = translate.keys.collect { | search | Regexp.escape(search) }
allsearch = Regexp.new(safesearch.join('|'))
print File.read(templatefile).gsub(allsearch) { | match | translate[match] }

-------------------------------------------------------------------


cheers
rickw





--
_________________________________
Rick Welykochy || Praxis Services

I think there is a world market for about five computers.
     -- Thomas Watson, IBM, 1943
--
SLUG - Sydney Linux User's Group Mailing List - http://slug.org.au/
Subscription info and FAQs: http://slug.org.au/faq/mailinglists.html

Reply via email to