From: Ross Bamford Date: 2006-04-12T21:21:03+09:00 Subject: Re: Simple substitutions Hi, On Wed, 2006-04-12 at 20:58 +0900, Peter Bailey wrote: > I have a need to parse postscript print files on a daily basis. Some of > them are over 10 mB. One thing I need to find out is the number of pages > in the files. There's a simple one-liner at the top of each .ps file > that states the number of pages. It reads: > %%Pages: xx > It's a line of its own. > > I simply want to find that line in my source file and then write a > corresponding line in my output file: > Number of pages: xx > > I tried the following in IRB, but I get the syntax error shown below. > > File.open("psout.txt", "w") do |output| > File.foreach("test1.ps") do |line| > line.sub!(/\%\%Pages: ([0-9]{1,5})/"Pages: \1"/) > output << line > end > end > > SyntaxError: compile error > (irb):26: parse error, unexpected tSTRING_BEG, expecting ')' > line.sub!(/\%\%Pages: ([0-9]{1,5})/"Pages: \1"/) > ^ > (irb):26: parse error, unexpected ')' > from (irb):29 > > Is there a significance to the ^ under the "P" in my syntax error? > What's it telling me? My sub requires parentheses. Is there a conflict > with my grouping parentheses inside my regular expression? > ruby is just complaining about a Perl-style s/// regexp. :) The correct syntax here would be something like: line.sub!(/\%\%Pages: ([0-9]{1,5})/) { "Pages: #$1" } (You can sometimes use the \1 escapes in the replacement but it's always come out hit-and-miss for me, so I stick to the block form). > Another request for help--my translation above would basically move the > entire contents of my source file to the target file, with the exception > of the one line I want changed. That's overkill for me. I just want a > few lines of information in my target file. Would you suggest I just do > a simple search, using matching (=~), and then write about that find in > my target file, or, would it be better to do mass deletions of > everything I don't want from my source to my target files? In other > words, should I say "in this file, find this, then say this . . ." or, > "convert this entire file, but just change this?" I would probably go with extracting just what I needed from the file, though if you can safely exclude portions of it before running matches (for example a large data section) that may improve performance. Also, I don't know if there are any Ruby postscript libraries, but it might be worth a search if you haven't already... Hope that helps, -- Ross Bamford - rosco@roscopeco.REMOVE.co.uk