Forum: Ruby Can you get the 1st occurrence of a value using grep?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Cf63da956b6ba955687a2f2f262928cb?d=identicon&s=25 Mmcolli00 Mom (mmcolli00)
on 2009-05-14 22:30
Can you get a 1st occurence of a sting inside a huge text file?

For instance, I  know that there will be 1 or more occurrences of a the
string 'fail' in a text file and I only want to get the first line
containing the 'fail' instead of getting every line with a fail. My
program reads over 100 files that may contain one or more 'fail' values.

Thanks
MC

Dir["//MYFile/*.txt"].each do |textfile|
    getGrepOffense = textfile.grep(/fail/)
    strOffense = getGrepOffense.join
    puts strOffense
end
Bb6ecee0238ef2461bef3416722b35c5?d=identicon&s=25 pat eyler (Guest)
on 2009-05-14 22:45
(Received via mailing list)
lines.detect {|l| l =~ /fail/}


On Thu, May 14, 2009 at 2:30 PM, Mmcolli00 Mom <mmc_collins@yahoo.com>
wrote:
> Dir["//MYFile/*.txt"].each do |textfile|
>    getGrepOffense = textfile.grep(/fail/)
>    strOffense = getGrepOffense.join
>    puts strOffense
> end
> --
> Posted via http://www.ruby-forum.com/.
>
>



--
thanks,
-pate
-------------------------
 Don't judge those who choose to sin differently than you do

http://on-ruby.blogspot.com
http://eldersjournal.blogspot.com
Cf63da956b6ba955687a2f2f262928cb?d=identicon&s=25 Mmcolli00 Mom (mmcolli00)
on 2009-05-14 23:20
Cool thanks! -MC
47b1910084592eb77a032bc7d8d1a84e?d=identicon&s=25 Joel VanderWerf (Guest)
on 2009-05-14 23:30
(Received via mailing list)
Mmcolli00 Mom wrote:
> Dir["//MYFile/*.txt"].each do |textfile|
>     getGrepOffense = textfile.grep(/fail/)
>     strOffense = getGrepOffense.join
>     puts strOffense
> end

[~/tmp] cat grepfail.rb
DATA.grep /fail/ do |line|
   p line
   break
end

__END__
ok 1
ok 2
fail 1
ok 3
fail 2
fail 3
[~/tmp] ruby grepfail.rb
"fail 1\n"

This should work with an open File in place of DATA.
This topic is locked and can not be replied to.