You can do this with a regex. Here is the line we want to find:
s = %{The first line The second line The third line The fourth line The fifth line The sixth line The seventh line The eight line The ninth line The tenth line }
EOL is "\ n" for me, but for you it could be "\ r \ n". I will stick with it in constant:
EOL = '\n'
To simplify the regular expression, we will define the template for the context only once:
CONTEXT_LINES = 2 CONTEXT = "((?:.*#{EOL}){#{CONTEXT_LINES}})"
And we will search for any string containing the word "fifth". Note that this regex must capture the entire line, including the end of the line, for it to work:
regexp = /.*fifth.*
Finally, do a search and show the results:
s =~ /^#{CONTEXT}(#{regexp})#{CONTEXT}/ before, match, after = $1, $2, $3 p before # => "The third line\nThe fourth line\n" p match # => "The fifth line\n" p after # => "The sixth line\nThe seventh line\n"
Wayne conrad
source share