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

M

Mmcolli00 Mom

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
 
P

pat eyler

lines.detect {|l| l =3D~ /fail/}


Can you get a 1st occurence of a sting inside a huge text file?

For instance, I =A0know 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|
=A0 =A0getGrepOffense =3D textfile.grep(/fail/)
=A0 =A0strOffense =3D getGrepOffense.join
=A0 =A0puts strOffense
end



--=20
thanks,
-pate
 
J

Joel VanderWerf

Mmcolli00 said:
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

[~/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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,981
Messages
2,570,188
Members
46,732
Latest member
ArronPalin

Latest Threads

Top