Getting into grep

Ronith
3 min readFeb 10, 2021

--

grep is one of the most useful UNIX commands; it makes the task of searching so much easier. I thought of collating my knowledge of this command in one place to be a goto guide for anyone who is a beginner to the terminal commands. In this tutorial, I will dwell into the various options and use cases of grep.

I will be using an example log file for this and demonstrate the search capabilities of grep.

1. grep <text> <file>

Grep by default is case-sensitive and returns the whole line containing the matching text.

grep "RSVP" sampleLogFile.log

2. select match only

-o is used to fetch just the matching part instead of the whole line

grep -o "RSVP" sampleLogFile.log

3. ignore-case

You can ask grep to ignore case by giving -i option.

grep -i “RSVP” sampleLogFile.log

4. invert match

-v can be used to fetch everything that does not match the search text

grep -v “RSVP” sampleLogFile.log

5. regex matching

What if you want to fetch all the IPs or search with a regex? grep also supports that with -E option!

grep -E “[0–9]+\.[0–9]+\.[0–9]+\.[0–9]+” sampleLogFile.log

do ignore the clumsy IP regex 😅

6. count

Although grep provides a way to count the text occurrences (well not exactly!), grep returns the count of lines having the text. So, if your search text is present multiple times per line, grep won’t be your biggest ally. Not to worry, I have got the perfect solution for this.

grep -oc “RSVP” sampleLogFile.log

this returns the count of lines containing the text “RSVP”

grep -o “RSVP” sampleLogFile.log | wc -l

this returns the actual count of the text “RSVP” in the file.

7. Output file name containing the search text

-l command gives the file names with the matching text instead of the usual text output.

grep -l “RSVP” sampleLogFile.log

One last use case of before we close this tutorial, what if you want lines with the text “RSVP” as well as an IP address? You can run a grep on your grep result. Let me show you how.

grep -i “RSVP” sampleLogFile.log | grep -E “([0–9]+\.){3}[0–9]+”

Here I am fetching the lines counting “RSVP” text, then grepping the lines with an IP in them. Such appending can be done n- number of times.

Thank you for reading.

--

--