I’ve searched for this a bit but I must be using the wrong terms – does ruby have a way to grep for a string/regex and also return the surrounding 5 lines (above and below)? I know I could just call "grep -C 5 ..."or even write my own method, but it seems like something ruby would have and I’m just not using the right search terms.
I’ve searched for this a bit but I must be using the wrong terms
Share
You can do it with a regular expression. Here’s the string we want to search:
EOL is “\n” for me, but for you it might be “\r\n”. I’ll stick it in a constant:
To simplify the regular expression, we’ll define the pattern for “context” just once:
And we’ll search for any line containing the word “fifth.” Note that this regular expression must grab the entire line, including the end-of-line, for it to work:
Finally, do the search and show the results: