Linux grep command filtering text with contextual search ( before , after , around )

Introduction:

In this article, you are going to learn how to perform the grep command with the "before," "after," and "around" match options. 

In the context of using grep in the command line, the terms "before," "after," and "around" the match refer to the ability to show additional lines of context surrounding the lines that match your search criteria. Here's how each option works:

Using this, we can easily filter text or log messages for daily operations. As a system administrator, knowing these features is crucial for the daily operation. Let's continue with the article.

Types of grep Contextual searches:

Using the -B (before) option allows you to display a certain number of lines before the match. 


The -A (after) option lets you display lines after the match. 


The -C (context) option is used to show lines both before and after the match. 


Examples and usage of grep command with After the Match:

Suppose you want to find the word "error" in server.log and see the three lines following it to understand the events after the error occurred.

$ grep -A 3 'error' server.log

Examples and usage of grep command with Before the Match:

If you're looking to see what happened right before an "error" in the same server.log file, you could display the two lines preceding it:

$ grep -B 2 'error' server.log

Examples and usage of grep command with Around the Match:

This command is particularly handy because it combines the functionality of -A and -B, giving you a full picture of the context surrounding your search term.

$ grep -C 3 'error' server.log

Conclusion:

To finish, we have seen how to use grep command with 'before', 'after', and 'around' options.  These options help us to see extra lines around the lines we are interested in.  This is very helpful for us to understand our text or log files better in our day-to-day work. 

Every system administrator should know how to use these features.  

It makes our work easy and fast. I hope this article helps you to learn these commands well.  Keep practicing and use them in your work. Thank you for reading.