#Linux : use grep to extract lines around a pattern match
In the text processing toolkit of every sys admin or data scientist out there there is a well known command line utility of which utility is second to none (ok, maybe sed is a strong contender): grep.
So “grepping” has become a known term among developers and it has the same meaning as “googling”, that is find something that matches my query in this file. Grep will return the list of rows matching the specified pattern.
However sometimes it is useful to have some context around the pattern match, especially if we are talking about system logs; in this case grep has a couple of little known flags that are super useful: -A
, for after the pattern match, and -B
for before.
For example to display 10 lines before and 15 lines after any system log line that contains the word error:
#journalctl --no-pager | grep "error" -A 15 -B 10
Posted on January 24, 2019, in Linux, Tips & Tricks and tagged command line tools, grep, log, sysadmin, text processing. Bookmark the permalink. 1 Comment.
Pingback: #Linux : extract substring in #Bash | whitehatty