From: Vidar Hokstad Date: 2006-10-11T23:40:07+09:00 Subject: Re: scanning strings, backward? Bil Kleb wrote: > Vidar Hokstad wrote: > > Bil Kleb wrote: > >> 1) Goto line 1707 of the file > >> 2) Search backward until line.match /\Wdt\W/i > >> 3) Remove /dt/i > > > > For 2) Any particular reason why you need to search backwards? My > > suggestion would be to look at String#gsub - that will help you handle > > both 2) and 3) in one go. > > The problem is I only want to replace only > the first occurrence before line 1707. If you use IO#readlines you're working on an array of lines one by one. So you'd do something like this: data = IO::readlines("test.txt") data_to_replace.each do |r| (0..(r[:lineno]-1)).times { |i| data[lineno].gsub!(r[:pattern],"") } end Assuming "data_to_replace" contains an array of arrays each containing :lineno => line number to stop at, and :pattern contains the pattern to delete. If the pattern can occur multiple times per line you need to do slightly more work, but gsub!() can take a block so you have full control over what you do with the matches. Vidar