6

これを少し検索しましたが、間違った用語を使用しているに違いありません.rubyには、文字列/正規表現をgrepし、周囲の5行(上下)を返す方法がありますか? 私は自分のメソッドを呼び出したり、書いたりすることさえできることを知って"grep -C 5 ..."いますが、それはRubyが持っているもののように思え、正しい検索用語を使用していません.

4

3 に答える 3

6

正規表現でできます。検索する文字列は次のとおりです。

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\n」かもしれません。私はそれを定数に貼り付けます:

EOL = '\n'

正規表現を単純化するために、「コンテキスト」のパターンを 1 回だけ定義します。

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

そして、「fifth」という単語を含む行を検索します。この正規表現が機能するには、行末を含む行全体を取得する必要があることに注意してください。

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

最後に、検索を実行して結果を表示します。

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"
于 2010-05-03T22:02:45.907 に答える
0

I don't think you can supply args to grep; based on the api.

You could always write a method. Something along the lines of this:

def new_grep(enum, pattern, lines)
 values = enum.grep(/pattern/).map do |x| 
   index = enum.index(x)
   i = (index - lines < 0) ? 0 : index - lines
   j = (index + lines >= enum.length) ? enum.length-1 : index + lines 
   enum[i..j]
 end
 return values.flatten.uniq
end
于 2010-05-03T20:41:33.090 に答える