2012-09-16 10 views
59

こんにちは、私はプログラミングをバッシュするのがとても新しいです。私はあるテキストで検索する方法を欲しい。そのために私はgrep関数を使用します:bashでgrepの結果の前後に行をフェッチする方法は?

grep -i "my_regex" 

それは機能します。しかし、このようなdata与えられた:私は(grep -i error dataを使用して)単語errorを見つけたら

This is the test data 
This is the error data as follows 
. . . 
. . . . 
. . . . . . 
. . . . . . . . . 
Error data ends 

、私は言葉error、次の10行を見つけたいです。だから私の出力は:

. . . 
    . . . . 
    . . . . . . 
    . . . . . . . . . 
    Error data ends 

どのような方法がありますか?

+0

あなたの説明から、10行が 'error'という単語に進んでいるように思えます。 – ThomasW

答えて

129

-B-Aを使用して、マッチの前と後の行を印刷できます。

grep -i -B 10 'error' data 

一致する行自体を含めて、一致する前に10行を印刷します。

+0

ありがとうございました。しかし、 'test = $(grep -i -B 10 'error' data)'のような変数にこの実行を保存しようとしたときに 'echo $ test'を使って出力すると、出力として直線の長い行が得られます。 – sriram

+1

ありがとう私は、 'echo $ test'ではなく、' echo "$ test" 'のようにする必要があることを理解しました。 – sriram

+1

' -C 10'は10行をANDで出力します。 –

5

これを試してみてください:

grep -i -A 10 "my_regex" 

-A 10手段、印刷を10行試合後は "my_regex" に

8

これを行う方法は、manページ

grep -i -A 10 'error data' 
の頂上付近にあります
3

これは、行の一致後に10行の末尾コンテキストを出力します。

grep -i "my_regex" -A 10 

あなたが

grep -i "my_regex" -B 10 

、行に一致する前に、一流のコンテキストの10行を印刷する必要がある場合そして、あなたは、先頭と末尾の出力コンテキストの10行を印刷する必要がある場合。

grep -i "my_regex" -C 10 

[email protected]:~$ cat out 
line 1 
line 2 
line 3 
line 4 
line 5 my_regex 
line 6 
line 7 
line 8 
line 9 
[email protected]:~$ 

通常のgrep

[email protected]:~$ grep my_regex out 
line 5 my_regex 
[email protected]:~$ 

Grepの正確な一致線と2行

Grepの正確な一致線と2行

[email protected]:~$ grep -B 2 my_regex out 
line 3 
line 4 
line 5 my_regex 
[email protected]:~$ 

Grepの正確な一致線と2つのライン前後

[email protected]:~$ grep -C 2 my_regex out 
line 3 
line 4 
line 5 my_regex 
line 6 
line 7 
[email protected]:~$ 

リファレンス前:マンページのgrep

-A num 
--after-context=num 

    Print num lines of trailing context after matching lines. 
-B num 
--before-context=num 

    Print num lines of leading context before matching lines. 
-C num 
-num 
--context=num 

    Print num lines of leading and trailing output context. 
関連する問題