[grep] Show lines before and after a match

Created on November 30, 2026

Use -A for lines after a match, -B for lines before it, or -C for both. This example includes one line on each side of ERROR.

printf 'line1\nline2\nERROR\nline4\nline5\n' | grep -C 1 'ERROR'
line2
ERROR
line4

The long options are --after-context, --before-context, and --context, respectively.

Reference

Shell command grep