一般 grep 只會將出現關鍵字的那一行文字顯示出來,例如:
johnroyer@box:~/logs$ zgrep 'parse' *gz
2016-02-27.log.gz:[2016-02-27 12:00:35] local.INFO: DOMDocument cannot parse XML: Premature end of data in tag html line 2
2016-02-27.log.gz:[2016-02-27 12:00:36] local.INFO: DOMDocument cannot parse XML: Premature end of data in tag html line 2
2016-02-27.log.gz:[2016-02-27 12:01:08] local.INFO: DOMDocument cannot parse XML: Premature end of data in tag html line 2
....
但有時顯示出來的訊息只是 function call stack trace 的其中一行,單看這一行無法理解到底發生了什麼事情。
遇到這種情況時,可以透過參數「-A」和「-B」來設定保留前後文:
johnroyer@box:~/logs$ zgrep 'Exception' *.gz -A 5 -B 2
[2016-05-29 23:41:22] production.INFO: RuntimeException: https://theinitium.com/newsfeed/
[2016-05-29 23:41:22] production.INFO: DOMDocument cannot parse XML: PCDATA invalid Char value 8
[2016-05-29 23:41:23] production.ERROR: exception 'RuntimeException' with message 'Invalid host label, check its content' in /home/segm/prod/www-crawler/vendor/league/url/src/Components/Host.php:164
Stack trace:
#0 /home/segm/prod/www-crawler/vendor/league/url/src/Components/AbstractSegment.php(47): LeagueUrlComponentsHost->validate('rss_Content.jsp')
#1 /home/segm/prod/www-crawler/vendor/league/url/src/Components/AbstractSegment.php(39): LeagueUrlComponentsAbstractSegment->set('rss_Content.jsp')
#2 /home/segm/prod/www-crawler/vendor/league/url/src/Components/Host.php(72): LeagueUrlComponentsAbstractSegment->__construct('rss_Content.jsp')
#3 /home/segm/prod/www-crawler/vendor/league/url/src/AbstractUrl.php(226): LeagueUrlComponentsHost->__construct('rss_Content.jsp')
.....
上面的範例是關鍵字前保留 2 行,往後保留 5 行。