2021-08-23 grep and context lines

Sometimes (well, actually pretty often!) I need to search text files with grep. By default, it displays all the lines that are matched by some regular expression. As is usual with heavily-used and battle-tested shell commands, it has numerous useful arguments, like -H and -h (print or suppress the filename prefix in every line), -n (print the line number along with the matching line) and many others. A few weeks ago, however, I had an extremely specific need, and I was very pleasantly surprised that grep supported precisely my use-case. I wanted to grep a log file having a particularly annoying format, and I wanted grep to display every match together with one preceding and two following lines.

Well, it turns out that grep has such a feature, too. It was enough to say grep -B 1 -A 2 pattern.

It is a fantastic feeling when the tools you use are actually useful and well thought out.

CategoryEnglish, CategoryBlog