grep is a search utility for finding strings and patterns in files and console input. By default, it prints the line that contains the match, but it’s also useful to print out the preceding lines around a match for context.
Printing Context For grep Matches
grep, you can add the uppercase
-C flag for “context,” which will print out N number of lines before and after the match. This can be quite useful for searching through code files, or anything else where you need to read what’s going on around the match.
grep -C 4 "foo" file
This is a common enough command that you don’t actually need to specify the
-C flag if it’s between 1-9, you can just use a flag like
-4 for 4 lines of context:
grep -4 "foo" file
If there are multiple matches,
grep will display a delimiter between them, except if they’re close enough to be within context of each other. When you have multiple matches, it’s also useful to display line numbers with the
-n flag so you can see where the match is located in the file.
grep -4 -n "foo" file
You can also manually specify how many lines you want before and after with
-B for before and
-A for after. Make sure not to mix these up with “above and below,” because that would be backwards.
grep -A 1 -B 3 "foo" file