From: Brian Candler Date: 2003-05-02T16:59:02+09:00 Subject: Re: Search string in a file On Fri, May 02, 2003 at 11:51:11AM +0900, Daniel Carrera wrote: > On Fri, May 02, 2003 at 10:04:09AM +0900, Panther wrote: > > I must search string in a file ?? > > How I must open file in read and search string ?? > > What is syntax ?? > > Thamk you > > Is this what you want?: > > dcarrera ~ $ cat > file > cat > dog > mouse > eagle > dcarrera ~ $ irb > >> File.readlines("file").each { |line| puts line if line =~ /o/ } > dog > mouse > >> Perhaps better not to read the whole file in at once, but process it line at a time: File.open("file").each_line { |line| puts line if line =~ /o/) If you want to collect the results into an array, then simply res = File.open("file").grep(/o/) or res = File.open("file") do |f| f.grep(/o/) end The second form is a bit longer but has the advantage that the file will be closed immediately after reading. The first form won't do this until garbage-collection takes place. Regards, Brian.