HomeTechnologyNewsHow to show surrounding lines around matches with grep for Linux

How to show surrounding lines around matches with grep for Linux

- Advertisement -
- Advertisement -
- Advertisement -
- Advertisement -

grep is a search utility for finding strings and patterns in files and console input. By default, it prints the line containing the match, but it is also useful to print the previous lines around a match by context.

Print context for grep matches

when you use grepyou can add the capitals -C flag for “context”, which will print 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 fairly common command that you don’t actually need to specify the -C flag if it is between 1 and 9, you can 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 are close enough to be in context with each other. When you have multiple matches, it is also useful to display the 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 later. Make sure you don’t mix them with “up and down”, because it would be the other way around.

grep -A 1 -B 3 "foo" file

- Advertisement -
- Advertisement -
Stay Connected
Must Read
- Advertisement -
Related News
- Advertisement -
%d bloggers like this: