Ruby等价于“grep -C 5”获得围绕比赛的线条的背景? [英] Ruby equivalent to "grep -C 5" to get context of lines around the match?

查看:109
本文介绍了Ruby等价于“grep -C 5”获得围绕比赛的线条的背景?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经搜索了一下,但是我必须使用错误的术语 - ruby​​是否有办法grep一个字符串/正则表达式,并返回周围5行(上下)?我知道我可以调用grep -C 5 ...甚至编写我自己的方法,但它看起来像ruby会有的,我只是没有使用正确的搜索条件。

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.

推荐答案

你可以用正则表达式来做到这一点。这是我们要搜索的字符串:

You can do it with a regular expression. Here's the string we want to search:

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对我来说是\ n,但对于您来说可能是\r\\\
。我将坚持在一个常数:

EOL is "\n" for me, but for you it might be "\r\n". I'll stick it in a constant:

EOL = '\n'

为了简化正则表达式,我们将定义context的模式一次:

To simplify the regular expression, we'll define the pattern for "context" just once:

CONTEXT_LINES = 2
CONTEXT = "((?:.*#{EOL}){#{CONTEXT_LINES}})"

我们将搜索包含单词five的任何行。请注意,这个正则表达式必须抓住整行,包括行尾,才能工作:

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:

regexp = /.*fifth.*#{EOL}/

最后,执行搜索并显示结果:

Finally, do the 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"

这篇关于Ruby等价于“grep -C 5”获得围绕比赛的线条的背景?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆