Robert Klemme
10/15/2003 1:11:00 PM
"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