Reading only certain rows of data from a text file

Hi Everyone,
My name is Jay, I’m new to the forum as well as fairly new to Ruby. I am
writing a program with File.open to read a text file, however need help
on a code that would only read certain rows of this large file. I am
basically only trying to get the rows where the first column has ‘cdtr’
(example)
in the data field.

I appreciate any help on this and thank you in advance.
Jay

On Fri, Jun 22, 2012 at 5:37 PM, Jason P. [email protected]
wrote:

Hi Everyone,
My name is Jay, I’m new to the forum as well as fairly new to Ruby. I am
writing a program with File.open to read a text file, however need help
on a code that would only read certain rows of this large file. I am
basically only trying to get the rows where the first column has ‘cdtr’
(example)
in the data field.

I appreciate any help on this and thank you in advance.

You could use File#foreach and a condition on the line, maybe a
regular expression. For example:

File.foreach(“file.txt”) do |line|
next unless line =~ /^cdtr/
do_something_useful_with line
end

You will most probably need to tweak the regular expression to your
needs. In the example I’m checking that the line starts with “cdtr”,
but maybe your condition is more complex, depending on the format of
your file.

Jesus.

I will give it a try and play with it if necessary. Will I still need to
call the (‘Path/file’) first with the File.open function?

Thank you Jesus,
Jay

Thank you for all your help and the link Jesus! Jay

On Fri, Jun 22, 2012 at 5:46 PM, Jason P. [email protected]
wrote:

I will give it a try and play with it if necessary. Will I still need to
call the (‘Path/file’) first with the File.open function?

No, if you use File.foreach you don’t need to use File.open method,
File.foreach opens the file and yields line by line to the block.

Jesus.