From: Jeremy Bopp Date: 2010-09-18T11:43:19+09:00 Subject: Re: search and replace On 09/17/2010 07:51 PM, John Smith wrote: > Jeremy Bopp wrote: >> On 9/17/2010 2:02 PM, John Smith wrote: >>> Hi everyone, >>> >>> I want to be able to run a program that will do a bunch >>> of searches specified in an array of strings, and replace the >>> first occurrence of those strings with strings specified on a >>> second array for a given text file. >>> >>> What would be the best way to do this? >> >> Maybe something like this: >> >> changes = [ >> ['string1', 'replacement1'], >> ['string2', 'replacement2'], >> ... >> ] >> >> File.open('somefile') do |f| >> f.each do |line| >> line_changed = false >> changes.each do |search, replacement| >> if line.sub!(search, replacement) then >> line_changed = true >> puts line >> break >> end >> end >> puts line unless line_changed >> end >> end >> >> >> -Jeremy > > That one almost works but it needs to do the > replacement only the first occurrence. What's > the easiest way to fix it to do that. I'm thinking of > a 'detect' but I'm not sure where I'd put it. > I'm not sure what you mean by only replacing the first occurrence. Are you saying that there could be more than 1 line in the file which could match a given search string but that you only want the first one of those to be processed? Maybe you could give a trivial example of some kind showing what you have and what you want to get. -Jeremy