パイプでgrepして複数行表示

パイプでgrepして複数行表示

grep大容量のテキストファイルを検索し、複数のキーワードを含む段落を返すためにそれを使用しようとしています。また、結果から周囲の行を返したいと思います。たとえば、青、緑、黄色という単語を検索したいとします。 "colors.txt"というファイルで3つの単語がすべて含まれている段落を見つけるには、次のコードを試しました。

grep blue colors.txt | grep green | grep yellow

ただし、これは黄色、緑、青を含む段落リストではなく、黄色のリストのみを提供します。

その後、周辺の単語を表示したいので、次のようなものを使用しました。

grep -B 5 blue colors.txt | grep green colors.txtその他など

とにかく - 大きなテキストファイルがあり、3つの色を含むセクションを探して、その周りに線を表示したいと思います。

ベストアンサー1

perl -00 -n -e 'print if (m/blue/i && m/green/i && m/yellow/i)' filename

perl段落読み取りモード()を使用して、3つの単語を-00すべて含む段落のみを印刷します(大文字と小文字の区別が一致)。

「段落」は、1つ以上の空行で、他の段落と区別された1つ以上のテキスト行です。

たとえば、あなたの質問テキストをファイルに保存し、perlそのファイルに次の行を実行しました。出力は次のとおりです

i am trying to use grep to search a large text file, and return the
paragraph containing a few key words. I also want to return the
surrounding lines in the result. So, for example I have the following
words I am going to search for: blue, green, yellow. If I wanted to find
the paragraph containing all 3 words, in the file called 'colors.txt', I
tried the following code:

grep blue colors.txt | grep green | grep yellow

This only gave me the listings for yellow though, and not the ones that
had yellow, green and blue, in the paragraph.

つまり、出力セグメントは3つだけですが、質問にはセグメントが7つあります。

おすすめ記事