From: Josh Cheek Date: 2011-04-27T13:27:53+09:00 Subject: Re: pattern matching and array methods --bcaec548a06716698604a1dedd10 Content-Type: text/plain; charset=ISO-8859-1 On Tue, Apr 26, 2011 at 11:07 PM, Mfer Dez wrote: > I have a text file that is structured like so: > > 1:1 abcdefg > 1:2 abcdefg > 1:3 abcdefg > 1:4 abcdefg > 1:5 abcdefg > > I would like to be able to print out a subset of the file ie: print the > line beginning with 1:2 through the line beginning with 1:4 > > So far, I've started with this; > > lines = File.readlines("file.txt") > > This puts each line of the text file into an array, so the lines[] array > looks like this: > > line[0] is 1:1 abcdefg > line[1] is 1:2 abcdefg > line[2] is 1:3 abcdefg > etc. > > If I want to print out the lines that start with 1:2 through 1:4, how > should I proceed? Some of the text files won't be "aligned" in that > line[0] won't always be 1:1. If a user would like to print the lines > containing 3:9 - 3:31, how can I scan each line of the array and pattern > match the boundaries (3:9 - 3:31 in this example)? What array methods > are available to me. > > Thanks in advance for any information that could point me in the right > direction. > > -- > Posted via http://www.ruby-forum.com/. > > I suppose you could use a flip flop... or awk :P $ cat file.txt 1:1 abcdefg 1:2 abcdefg 1:3 abcdefg 1:4 abcdefg 1:5 abcdefg $ ruby -e ' > File.foreach ARGV.first do |line| > puts line if line.start_with?("1:2")..line.start_with?("1:4") > end > ' file.txt 1:2 abcdefg 1:3 abcdefg 1:4 abcdefg $ awk '$1 == "1:2", $1 == "1:4"' file.txt 1:2 abcdefg 1:3 abcdefg 1:4 abcdefg --bcaec548a06716698604a1dedd10--