Use the -C flag to show the lines of context around the matching search term. This is basically the same as using -A and -B together.
Let’s return back to our file test.txt with the following content:
sad
happy
awake
coffee
work
schoolAs before, we would search for the word “happy” like this:
$ grep "happy" test.txt
happyTo see the first line before and after happy, execute the following:
$ grep -C 1 "happy" test.txt
sad
happy
awakeThe lowercase version of this flag (-c) is also pretty useful. This will show the number of lines that the matching term shows up in.
For example:
grep -c "happy" test.txt
1Let’s add another happy line and try the flag again:
echo "happy" >> test.txt
grep -c "happy" test.txt
2It’s important to note that -c will only return the number of lines. If we added another line with multiple “happy” words, it will only be counted once.
echo "happy happy happy" >> test.txt
grep -c "happy" test.txt
3 Want to see this in action? Check out the video below.