How to search in files and show the lines before and after

Let’s see how to search in files and show the lines before and after the coincidences. Very useful when searching in log files, for example.

How to search in files and show the lines before and after

Let’s see an easy example:

grep -C 30 'error' error.log

This script will output the 30 lines (15 before and 15 after) for each coincidence searching error in the file error.log.

You can change the number of lines, the value to search and the file(s) to search in. Also, keep in mind can use commodins:

grep -C 2 '*@gmail.com' *.log
```bash

This script will output the 2 lines (1 before and 1 after) for any coincidence ending with `@gmail.com` in any `.log` file.

Feel free to leave a comment with your doubts or experiences.


David Burgos

Read more posts by this author.