Posted By

scruffpuff on 11/07/11


Tagged

file io String


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

collegeimprovements


Finding strings in Files in Ruby


 / Published in: Ruby
 

  1. Simplest
  2. fgrep 'mystring' filename.txt
  3.  
  4. Now it depends on whether to just verify the string is there:
  5.  
  6. def check_file( file, string )
  7. File.open( file ) do |io|
  8. io.each {|line| line.chomp! ; return true if line.include? string}
  9. end
  10.  
  11. false
  12. end
  13.  
  14. or whether to get the first matching line:
  15.  
  16. def check_file( file, string )
  17. File.open( file ) do |io|
  18. io.each {|line| line.chomp! ; return line if line.include? string}
  19. end
  20.  
  21. nil
  22. end
  23.  
  24. or whether to get all matching lines:
  25.  
  26. def check_file( file, string )
  27. lines=[]
  28.  
  29. File.open( file ) do |io|
  30. io.each {|line| line.chomp! ; lines << line if line.include? string}
  31. end
  32.  
  33. lines
  34. end
  35.  
  36. or whether the condition is a regexp:
  37.  
  38. def check_file( file, rx )
  39. File.open( file ) do |io|
  40. io.each {|line| line.chomp! ; return true if rx =~ line}
  41. end
  42.  
  43. false
  44. end

Report this snippet  

You need to login to post a comment.