If you want to show surrounding lines around matches in a Linux command line, there are a few ways to do it. The simplest way is to use the grep command. For example, to show the lines around the match in the file test.txt that contains the word “cat,” you could use this command: grep cat test.txt This will output the lines that contain the word “cat” in test.txt. ..
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.
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:
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.
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.