Quick Earn Money

How do I grep and show the preceding and following 5 lines surrounding each matched line?

 

To grep and show the preceding and following 5 lines surrounding each matched line, you can use the grep command in combination with the -C (context) option. Here's how you can do it:

bash
grep -C 5 "search_pattern" file.txt

Replace "search_pattern" with the pattern you want to search for and file.txt with the name of the file you want to search within.

This command will display the lines that match the search pattern along with the 5 lines before and after each match.

Here's an example:

Suppose you have a file named example.txt with the following content:

scss
Line 1 Line 2 Line 3 - Matched line Line 4 Line 5 Line 6 Line 7 Line 8 Line 9

If you want to search for the pattern "Matched line" and display the 5 lines before and after each match, you can run the following command:

bash
grep -C 5 "Matched line" example.txt

The output will be:

scss
Line 2 Line 3 - Matched line Line 4 Line 5 Line 6

This output shows the matched line along with the 5 lines before and after it. The -C option specifies the number of lines of context to display around each match, and in this case, it's set to 5.

Comments