程式扎記: [Linux 常見問題] Grep a file, but show several surrounding lines?

標籤

2016年11月6日 星期日

[Linux 常見問題] Grep a file, but show several surrounding lines?

Source From Here
Question
I would like to grep for a string, but also show the preceding five lines and the following five lines as well as the matched line. I'm scanning for errors in a logfile, and want to see the context.

How-To
For BSD or GNU grep you can use -B num to set how many lines before the match and -A num for the number of lines after the match.
$ grep 'line4' test.txt
This is test line4
line4-1
line4-2
line4-3
line4-4


// -B NUM, --before-context=NUM: Print NUM lines of leading context before matching lines.
$ grep -B 2 'line4' test.txt
This is test line2
This is test line3

This is test line4
line4-1
line4-2
line4-3
line4-4


// -A NUM, --after-context=NUM: Print NUM lines of trailing context after matching lines.
$ grep -A 2 'line4' test.txt
This is test line4
line4-1
line4-2
line4-3
line4-4
This is test line5
This is test line6


沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!