Linux grep command – Part 1
grep (short for Global Regular Expression Print) is a command line tool used to search for a particular pattern of characters and prints out all the lines that contain that pattern.
Usually the grep command is installed by default on most Linux distributions. You can run grep ‐‐version in the terminal to check if the command in installed.

If it’s not installed, it’s easy to do it, you just have to run sudo apt-get install grep.
I will cover the grep command in a couple of posts as this is one of the most used/useful commands on Linux/Unix systems and offers a lot of options.
The syntax for grep is:
grep [option] pattern [file]
Please keep in mind that the grep command can be used in combination with other commands. For example ls -> ls -l | grep [option] pattern [file]. Also, the grep command can be used without the option operator or file path, depending on the situation.
How it works
As a first example, let say we want to list all the files/directories that contain the term example.

Or let’s search for a string within a file

grep commands are case sensitive, in order to avoid this we can use the -i operator. Running the command with this option will print lowercase and uppercase results.

grep -c
If we run the grep command with the -c operator it will print the number of matches and not the match itself.

I have used the i operator along with c in order to count the lowercase and uppercase results.
grep -n
Using the -n operator will display the line number for each matching line.


grep -o
By default, the grep command will print the full line which contains the matching pattern (you can see in the example from the -n, where we searched for “lorem” but the whole line was displayed).
grep -o will print only the matching pattern.

This is the end of the first post about the grep command. I will cover more options in the next one.
Thank you for reading.
