[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: Search string in a file

Chad Fowler

10/15/2003 12:24:00 PM

3 Answers

Robert Klemme

10/15/2003 1:11:00 PM

0


"Chad Fowler" <chad@chadfowler.com> schrieb im Newsbeitrag
news:Pine.LNX.4.44.0310150841280.26441-100000@ns1.chadfowler.com...
> On Wed, 15 Oct 2003, Panther wrote:
>
> # I must search string in a file ??
> # How I must open file in read and search string ??
> # What is syntax ??
> # Thamk you
> #
>
> ruby -ne 'print if /mystring/' filename.txt

I guess the OP is searching for a ruby solution, that can be embedded in a
script. Otherwise this is likely to be simpler and more efficient:

fgrep 'mystring' filename.txt

Now it depends on whether to just verify the string is there:

def check_file( file, string )
File.open( file ) do |io|
io.each {|line| line.chomp! ; return true if line.include? string}
end

false
end

or whether to get the first matching line:

def check_file( file, string )
File.open( file ) do |io|
io.each {|line| line.chomp! ; return line if line.include? string}
end

nil
end

or whether to get all matching lines:

def check_file( file, string )
lines=[]

File.open( file ) do |io|
io.each {|line| line.chomp! ; lines << line if line.include? string}
end

lines
end

or whether the condition is a regexp:

def check_file( file, rx )
File.open( file ) do |io|
io.each {|line| line.chomp! ; return true if rx =~ line}
end

false
end

etc.

Cheers

robert

Jason Williams

10/15/2003 1:22:00 PM

0

In article <bmjh13$nopuc$1@ID-52924.news.uni-berlin.de>, Robert Klemme wrote:
>> ruby -ne 'print if /mystring/' filename.txt
>
> I guess the OP is searching for a ruby solution, that can be embedded in a
> script. Otherwise this is likely to be simpler and more efficient:
>
> fgrep 'mystring' filename.txt
>
> [...snip...]

How about

file.grep(/mystring/) { |s| puts s }

?

Robert Klemme

10/15/2003 1:32:00 PM

0


"Jason Williams" <jason@jasonandali.org.uk> schrieb im Newsbeitrag
news:slrnboqige.dt.jason@kotu.jasonandalishouse.org.uk...
> In article <bmjh13$nopuc$1@ID-52924.news.uni-berlin.de>, Robert Klemme
wrote:
> >> ruby -ne 'print if /mystring/' filename.txt
> >
> > I guess the OP is searching for a ruby solution, that can be embedded
in a
> > script. Otherwise this is likely to be simpler and more efficient:
> >
> > fgrep 'mystring' filename.txt
> >
> > [...snip...]
>
> How about
>
> file.grep(/mystring/) { |s| puts s }

I guess you mean:

File.open( file ) {|io| io.grep(/mystring/) { |s| puts s }}
or
File.open( file ) {|io| io.grep(/mystring/)}

That doesn't get rid of line terminations. One can do

File.open( file ) {|io| io.grep(/mystring/).each{|line|line.chomp!}}

Yes, that's nicer if one does not want the simple check / first line. In
those cases it's more efficient for large files to short circuit at the
first match.

Cheers

robert