How To Use grep Command (With Examples)

Grep short for Global Regular Expression Print is a command line utility for searching lines in text based data to match a particular regular expression.  

How to use grep command

​Grep is extremely simple to use, I have a text file on my Desktop with the following text. Now let’s say we need to search for a particular pattern from this file, we can do that by using the following command.grep “pattern to match” filename​In this case, we will use the following command to match the pattern “various”.grep “various” LinuxAndUbuntu.txt

search text using grep command

You can see that our text files 5th line had the pattern “various” in it, grep has printed the entire line containing that pattern.

We can also get the line number of the match by simply adding a -n to the command.

You can see in the image below that we searched for the word “technological” and it returned two matches. On the left side of the printed line, we can see the line number.

grep
grep

Now I have created another file called LNU.txt which has the following lines of text as follows.

It is in the same directory as my first file.

text to use grep linux command

Now if I wanted to search for a pattern or expression in all those files I would just put a * instead of the filename. It would mean that grep must search in all files in that directory.

I will use the following command for this. grep -n “technolog” *

grep command with examples

You can see in the image below that along with the line numbers, the name of the file matching the pattern is also printed.

If you wish to search for a phrase that starts and end with some specific expression you can do that using .*. For instance, if we wanted to search for all instances where a phrase begins with free and ends with source we could use the following command. grep -n ‘free.*source’ LinuxAndUbuntu.txt

grep linux command

As you can see in the image above that we searched for a phrase that begins with free and ended with a source. We found a match that was ‘free and open source’.So that was a quick and concise tutorial on how to use the grep command. The grep command is extremely powerful with many options.

You can check out all of these options by simply typing grep –help.

grep help command
grep help command

SHARE THIS POST

MassiveGRID Banner

Leave a Reply

Your email address will not be published. Required fields are marked *