From: John Smith Date: 2010-09-19T02:42:01+09:00 Subject: Re: search and replace Hmm it works perfect for what I asked.. but I realized I will probably need it more granular. Instead of the first occurrence within a file, the first ocurrence in a line. As of now it works, for this case: 1 4 1 5 1 4 1 5 one four 1 5 1 4 1 5 However, If we have : 1 4 1 4 1 5 it will put one four one four one 5 and I want: one four 1 4 1 5 From here I suppose it would be a matter of working with the line. Is there a command to replace first occurrence of a word in a line with another word? Something like: line.detect_first_occurrence_and replace("1", one). Ted. line_changed = true Jeremy Bopp wrote: > On 09/18/2010 11:14 AM, John Smith wrote: >> one four >> 1 4 >> 1 5 >> 1 4 >> 1 5 > > Alright, so you only want a search/replace pair to apply to a single > line in the file to be processed. After the search/replace pair has > been applied one time, it should be dropped from the list of pairs to > try so that it cannot be used on subsequent lines. Try this: > > changes = [ > ['string1', 'replacement1'], > ['string2', 'replacement2'], > ... > ] > > File.open('somefile') do |f| > f.each do |line| > line_changed = false > changes.each do |change| > if line.sub!(change[0], change[1]) then > line_changed = true > changes.delete(change) > puts line > break > end > end > puts line unless line_changed > end > end > > > -Jeremy -- Posted via http://www.ruby-forum.com/.