Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jun 17th, 2012  |  syntax: None  |  size: 0.50 KB  |  hits: 18  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. How do I retrieve only lines with specific words or phrases?
  2. lines = File.readlines("myfile.txt")
  3.        
  4. the red queen of hearts.
  5. yet another sentence.
  6. and this has no relevant words.
  7. the blue sky
  8. the white chocolate rabbit.
  9. another irrelevant line.
  10.        
  11. the red queen of hearts.
  12. the blue sky
  13. the white chocolate rabbit.
  14.        
  15. lines = File.readlines("myfile.txt").grep(/red|rabbit|blue/)
  16.        
  17. /^.*(red|rabbit|blue).*$/
  18.        
  19. lines.each do |line|
  20.     if line.include? red or rabbit or blue
  21.         puts line
  22.     end
  23. end