From: Peter Bailey Date: 2006-04-12T22:35:56+09:00 Subject: Re: Simple substitutions Ross Bamford wrote: > On Wed, 2006-04-12 at 22:04 +0900, Peter Bailey wrote: >> Now, I'd like to >> streamline my conversion and aim for the much smaller target file I >> mentioned above. Right now, my target file is still 10mB big, with just >> that one pages line replaced with what I want. So, instead of working in >> line mode, do you think I should just read in the entire file and use >> ".*" before and after my sub expression to get rid of everything else? >> > > Well, memory is cheap these days and I have to admit I'm much less > careful about how I use it (unless there's a specific reason to conserve > it) but in this case, if there's only one pages line in your file, then > how about doing something like (N.B. untested code): > > pages = nil > File.foreach("test1.ps") do |line| > if line =~ /\%\%Pages: ([0-9]{1,5})/ > pages = $1 > break > end > end > > if pages > File.open("psout.txt", "w") { |out| out << "Pages: #{pages}" } > end > > If you do choose to read the whole thing in at once, one way to achieve > that might be: > > pages = nil > File.read('test1.ps').scan(/\%\%Pages: ([0-9]{1,5})/) do > pages = $1 > break > end > > if pages > File.open("psout.txt", "w") { |out| out << "Pages: #{pages}" } > end Aha. I didn't know about "scan." Just the word alone makes sense for what I want. And, yes, I found it in the Big Book, on page 617. What does the "break" do, Ross? Is it just telling RUBY to stop if it's found what it was scanning for? This worked! I'm more prone to just read the whole file in. Thanks a lot, Ross! I feel I can move mountains now. -- Posted via http://www.ruby-forum.com/.