All Articles

The ABC's of grep - C

C

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
school

As before, we would search for the word “happy” like this:

$ grep "happy" test.txt
happy

To see the first line before and after happy, execute the following:

$ grep -C 1 "happy" test.txt
sad
happy
awake

The 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
1

Let’s add another happy line and try the flag again:

echo "happy" >> test.txt
grep -c "happy" test.txt
2

It’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.

Published Oct 25, 2023

I love coffee, coding and writing.