DEV Community

Cover image for "grep" Command In Linux/Unix
Enes Karataş
Enes Karataş

Posted on

"grep" Command In Linux/Unix

Getting Started With "grep"

➔ This tutorial is written to inform about grep command and its usage in Linux/UNIX system. In the next tutorials I am planning to share all the commands that I have used before.

Anyways, let's look at how to use the command.

How to use grep command ?

The grep command is one of the most useful linux command for linux users. It used to search given string or world in a file or process. It takes given string or word and returns including correct match.

The command is also stands for "Globally search for a Regular Expression and Print it out". There are some useful parameters that grep takes. We are going to use each other with grep in examples.

Examples

Firstly I've created test.txt to use as file. The content of this file like following.

   linuxuser@ubuntu:~/Desktop$ cat test.txt
Enter fullscreen mode Exit fullscreen mode
Username: User
Password: UserPassword
Name: John
Lastname: Doe
Adress: FakeStreet FakeCountry no: 24 postal: 00000

Enter fullscreen mode Exit fullscreen mode

To be able to find something in the file the simple usage of command can be used without parameter.

   linuxuser@ubuntu:~/Desktop$ grep Street test.txt
Enter fullscreen mode Exit fullscreen mode

Output will be like following.

   Adress: FakeStreet FakeCountry no: 24 postal: 00000
Enter fullscreen mode Exit fullscreen mode

In the terminal command above we searched for the word Street and get the line including Street.

We can also use -i parameter to search as case-insensitive.

   linuxuser@ubuntu:~/Desktop$ grep -i stReEt test.txt
Enter fullscreen mode Exit fullscreen mode

Output will be the same with first example.

   Adress: FakeStreet FakeCountry no: 24 postal: 00000
Enter fullscreen mode Exit fullscreen mode

‼️ Note that the grep function returns us a line where the given string is part of the word such as 'Street' and 'FakeStreet' so that if you want to search the line of the whole word matches you should use -w parameter.

   linuxuser@ubuntu:~/Desktop$ grep -w Username test.txt
Enter fullscreen mode Exit fullscreen mode

In the output below we could see given string in terminal command.

   Username: User
Enter fullscreen mode Exit fullscreen mode

To find line number with search result you can use -n parameter.

   linuxuser@ubuntu:~/Desktop$ grep -n Address test.txt
Enter fullscreen mode Exit fullscreen mode
   5:Address: FakeStreet FakeCountry no: 24 postal: 00000
Enter fullscreen mode Exit fullscreen mode

As you can see in the output there is line number like "5".

What if you want to know how many match line after running command ?
Sure there is a parameter to do that. -c parameter is used to count matches and also stands for count.

   linuxuser@ubuntu:~/Desktop$ grep -c "User" test.txt
Enter fullscreen mode Exit fullscreen mode
   2
Enter fullscreen mode Exit fullscreen mode

We got output "2" and if you go to content of test.txt you are going to see 2 line matches probably.

The -v option returns the all lines that don't contain a matches corresponding to the given string.

   linuxuser@ubuntu:~/Desktop$ grep -v User test.txt
Enter fullscreen mode Exit fullscreen mode
   Name: John
   Lastname: Doe
   Address: FakeStreet FakeCountry no: 24 postal: 00000
Enter fullscreen mode Exit fullscreen mode

There are some options like -B and -A that mean "BEFORE" and "AFTER" or at least you can think about it like that to make permanent in your mind 😉. So those options are used to get to the previous or next lines of matching lines.

   linuxuser@ubuntu:~/Desktop$ grep -A 1 User test.txt
Enter fullscreen mode Exit fullscreen mode
   Username: User
   Password: UserPassword
   Name: John
Enter fullscreen mode Exit fullscreen mode

In the output above there is one more line apart of the User matching lines that is Name: John. If you put 2 instead of 1 in the command above you probably are going to get two more lines. For instance:

   Username: User
   Password: UserPassword
   Name: John
   Lastname: Doe
Enter fullscreen mode Exit fullscreen mode

Let's try the other one with the same logic. This time we are going to use -B parameter.

   linuxuser@ubuntu:~/Desktop$ grep -B 2 User test.txt
Enter fullscreen mode Exit fullscreen mode

When we run out the command above we see the output like below. There are two more line before the matching lines as you can see in the output below.

   Name: John
   Lastname: Doe
   Address: FakeStreet FakeCountry no: 24 postal: 00000
Enter fullscreen mode Exit fullscreen mode

All the examples have been done using file so far. Let's use grep on different ways. For instance sometimes you use ping command in the both linux and windows. So you can also use grep with ping command. Let me show an instance here.

   ping 8.8.8.8 | grep -i ttl
Enter fullscreen mode Exit fullscreen mode

You probably get the same result so each of the successful response lines has ttl value. We need to search something that doesn't exist on each line. Suppose you want to check internet connection via ping.

   linuxuser@ubuntu:~$ping 8.8.8.8 | grep -i "Request timed out"
Enter fullscreen mode Exit fullscreen mode

Or

   linuxuser@ubuntu:~$ ping 8.8.8.8 | grep -i 'request timed out\ | host unreachable'
Enter fullscreen mode Exit fullscreen mode

The both request timed out and host unreachable will be searched on this way. You can increase the samples yourself.

Let's do some searching in the files under the directories.
To make searching under directory you need to use grep as recursively. To be able to do that -r or -R options can be used. Let's make a searching for the default router IPs using 192.168.1.5 address.

   linuxuser@ubuntu:~$ sudo grep -R "192.168.1.5" /etc/
Enter fullscreen mode Exit fullscreen mode
   /etc/ppp/options:# ms-wins 192.168.1.50
   /etc/ppp/options:# ms-wins 192.168.1.51
Enter fullscreen mode Exit fullscreen mode

The other example would be about your system information. Under the /proc directory there is a file named cpuinfo that contains information about your system. It is time to manipulate this file !

   linuxuser@ubuntu:~$ ls /proc
Enter fullscreen mode Exit fullscreen mode

The first we've listed the files and directories. Now we are going to write the content of cpuinfo file.

   linuxuser@ubuntu:~$ cat /proc/cpuinfo
Enter fullscreen mode Exit fullscreen mode
   processor    : 0
   vendor_id    : GenuineIntel
   cpu family   : 6
   model    : 140
   model name   : 11th Gen Intel(R) Core(TM) i5-1135G7 @ 2.40GHz
   stepping : 1
   microcode    : 0x86
   .
   .
   .
   .
Enter fullscreen mode Exit fullscreen mode

This is mine and you will get the result like this. Alright let's search something in this file using grep.

   linuxuser@ubuntu:~$ cat /proc/cpuinfo | grep -i cpu
Enter fullscreen mode Exit fullscreen mode
   cpu family   : 6
   cpu MHz  : 2419.199
   cpu cores    : 1
   cpuid level  : 27
Enter fullscreen mode Exit fullscreen mode

In the example above we've searched "cpu" word in cpuinfo file. So the same process also can be done using the command below.

   linuxuser@ubuntu:~$ grep -r cpu /proc/cpuinfo
Enter fullscreen mode Exit fullscreen mode

Let us take a look at what else we can do. We are going to create a bash script file and write something in this file. For instance the informations in the cpuinfo file can be written to another .txt file.

Creating a bash script file named file_script.sh.

   touch file_script.sh
Enter fullscreen mode Exit fullscreen mode

Editing on nano editor. That is my choice, you can also use another one else.

   nano file_script.sh
Enter fullscreen mode Exit fullscreen mode
   #!/bin/bash

   function write_to_file()
   {
        read -p "Enter file name(ex: filename.txt): " FILENAME
        SYSTEMINFO=$(cat /proc/cpuinfo | grep -i name)
        printf "%s\n" "$SYSTEMINFO" >> $FILENAME
   }

   write_to_file
Enter fullscreen mode Exit fullscreen mode

The content of script file is above and it can be improved more. Once you run out the code file you will need enter the file name where the searching is stored. When you see the inside of the file that you named on script you are going to see the searching result. If you don't want to show the file name while you write then you can use -s option before -p.

It is time to the last example now. Consider you have a file containing public domain list and you want to search for domains only containing .com on this file and extract to the other one.

Let's write this script !


function extract_domains()
{
        TARGETFILE='extracted.txt'
        FILENAME='domains.txt'
        _DOMAINS=$(cat $FILENAME | grep -i .com)

        printf "%s\n" "$_DOMAINS" >> $TARGETFILE

        FILE=$TARGETFILE
        if [ -f "$FILE" ]; then
                echo "$FILE exists. All the domains end with '.com' are extracted !"
        fi

}
extract_domains
Enter fullscreen mode Exit fullscreen mode
   extracted.txt exists. All the domains end with '.com' are extracted !

Enter fullscreen mode Exit fullscreen mode

Let us explain the code above. There is a file named domains.txt on your current directory. So the file stores public domain list and we've searched all the domains end with .com on the domains.txt. All searched domains are written to extracted.txt and checked if the file exists. If so then the output returned otherwise you would get the output like "file doesn't exists !".

Thank you so much for reading.
Have a good day !

Discussion (0)