On Tue, Apr 26, 2011 at 11:27 PM, Josh Cheek <josh.cheek / gmail.com> wrote:

>
> 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
>
>
Actually, you need a regex here, because start_with?("1:2") will match "1:23
abcdefg" for example. With a regex you can use \b to indicate the word
break, or if you can have leading whitespace, a regex can deal with that.


$ ruby -e '(1..40).each { |big| (1..40).each { |small| puts "#{big}:#{small}
blah" } }' |
> ruby -e '$stdin.each { |line| puts line if line[/^1:2\b/]..line[/^2:2\b/]
}'
1:2 blah
1:3 blah
1:4 blah
1:5 blah
1:6 blah
1:7 blah
1:8 blah
1:9 blah
1:10 blah
1:11 blah
1:12 blah
1:13 blah
1:14 blah
1:15 blah
1:16 blah
1:17 blah
1:18 blah
1:19 blah
1:20 blah
1:21 blah
1:22 blah
1:23 blah
1:24 blah
1:25 blah
1:26 blah
1:27 blah
1:28 blah
1:29 blah
1:30 blah
1:31 blah
1:32 blah
1:33 blah
1:34 blah
1:35 blah
1:36 blah
1:37 blah
1:38 blah
1:39 blah
1:40 blah
2:1 blah
2:2 blah


I don't really understand why everyone else is parsing the numbers. Perhaps
they assume these lines might not be in order?




On Tue, Apr 26, 2011 at 11:07 PM, Mfer Dez <emphxl / yahoo.com> wrote:

> 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.
>
>

For custom boundaries, you can just interpolate them into the regex

$ ruby -e '(1..40).each { |big| (1..40).each { |small| puts "#{big}:#{small}
blah" } }' |
> ruby -e '$stdin.each { |line| puts line if
line[/^#{ARGV[0]}\b/]..line[/^#{ARGV[1]}\b/] }' 3:9 3:31
3:9 blah
3:10 blah
3:11 blah
3:12 blah
3:13 blah
3:14 blah
3:15 blah
3:16 blah
3:17 blah
3:18 blah
3:19 blah
3:20 blah
3:21 blah
3:22 blah
3:23 blah
3:24 blah
3:25 blah
3:26 blah
3:27 blah
3:28 blah
3:29 blah
3:30 blah
3:31 blah


I'm reading these line by line from the file, that is most efficient (what
if your file is enormous, do you really want to read it all into an array?)
but the interface to an array is exactly the same, instead of iterating over
the file, you just iterate over the array. Just change $stdin.each to
$stdin.readlines.each, everything works the same, but uses an array now.

$ ruby -e '(1..40).each { |big| (1..40).each { |small| puts "#{big}:#{small}
blah" } }' |
> ruby -e '$stdin.readlines.each { |line| puts line if
line[/^#{ARGV[0]}\b/]..line[/^#{ARGV[1]}\b/] }' 3:9 3:31
3:9 blah
3:10 blah
3:11 blah
3:12 blah
3:13 blah
3:14 blah
3:15 blah
3:16 blah
3:17 blah
3:18 blah
3:19 blah
3:20 blah
3:21 blah
3:22 blah
3:23 blah
3:24 blah
3:25 blah
3:26 blah
3:27 blah
3:28 blah
3:29 blah
3:30 blah
3:31 blah