Technology

#How to Show Surrounding Lines Around Matches With grep for Linux

“How to Show Surrounding Lines Around Matches With grep for Linux”

Bash Shell

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

When using 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


If you liked the article, do not forget to share it with your friends. Follow us on Google News too, click on the star and choose us from your favorites.

For forums sites go to Forum.BuradaBiliyorum.Com

If you want to read more like this article, you can visit our Technology category.

Source

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button
Close

Please allow ads on our site

Please consider supporting us by disabling your ad blocker!