0

I need to read a file in a series of lines, and then retrieve specific lines depending on words that are contained in them. How can I do this?

So far I read the lines like this:

lines = File.readlines("myfile.txt")

Now, I need to scan for lines that contain "red", "rabbit", "blue". I want to do this part in as few lines of code as possible.

So if my file was:

the red queen of hearts.
yet another sentence.
and this has no relevant words.
the blue sky
the white chocolate rabbit.
another irrelevant line.

I would like to see only the lines:

the red queen of hearts.
the blue sky
the white chocolate rabbit.
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Flethuseo
  • 5,969
  • 11
  • 47
  • 71
  • I suppose you don't want lines that contain the strings "red", etc. You want lines that contain them as words. See my comment on floatless's answer. – sawa May 15 '11 at 20:30
  • Duplicate of [Finding lines in a text file matching a regular expression](http://stackoverflow.com/questions/6002868/finding-lines-in-a-text-file-matching-a-regular-expression) – Phrogz May 15 '11 at 21:33

3 Answers3

3
lines = File.readlines("myfile.txt").grep(/red|rabbit|blue/)
Daniel O'Hara
  • 13,307
  • 3
  • 46
  • 68
  • This will match lines that include "Fred", "jackrabbit", "bluer". The regex should be `/\b(?:red|rabbit|blue)\b/`. – sawa May 15 '11 at 20:28
1

Regular expressions are your friend. They will make quick work of this task.

http://www.tutorialspoint.com/ruby/ruby_regular_expressions.htm

You would want a regex along the lines of

/^.*(red|rabbit|blue).*$/

The ^ means start of line, the .* means match anything, (red|rabbit|blue) means exactly what you think it means, and lastly the $ means end of line.

Chris Eberle
  • 47,994
  • 12
  • 82
  • 119
0

I think an each loop would be best in this situation:

lines.each do |line|
    if line.include? red or rabbit or blue
        puts line
    end
end

Give that a shot.

Mark
  • 694
  • 5
  • 15