Global Regular Expression Print(GREP)

Regular Expressions, Pipelines & I/O Redirections Grep:
Grep stands for Global Regular Expression Print. It is used to pick out the required expression from the file and print the output. If grep is combined with another command it can be used to pick out the selected word, phrase from the output of first command and print it.

Examples of Grep:
Let us pick the information about root from the file /etc/passwd (/etc/passwd contains information about all the users present in the system)
#grep root /etc/passwd

[root@localhost ~]# grep root /etc/passwd
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
[root@localhost ~]#

To avoid case sensitivity of the word use -i
#grep –i linux linuxfile (lets grep the word linux whether upper of lower case in the file linuxfile)

[root@localhost ~]# grep -i linux linuxfile
Linux - RedHat
linux - centos
linux - ubuntu
[root@localhost ~]#

To display a word and 2 lines after the word:
#grep –nA2 wheel /etc/group

[root@localhost ~]# grep -nA2 wheel /etc/group
11:wheel:x:10:
12-cdrom:x:11:
13-mail:x:12:postfix
[root@localhost ~]#

To display a word and 2 lines after the word:
#grep –nB2 wheel /etc/group

[root@localhost ~]# grep -nB2 wheel /etc/group
9-mem:x:8:
10-kmem:x:9:
11:wheel:x:10:
[root@localhost ~]#

To display the things except the given word:
#grep –v linux linuxfile

[root@localhost ~]# cat linuxfile
linux - RedHat
linux - centos
linux - ubuntu
Hello World
[root@localhost ~]# grep -v linux linuxfile
Hello World
[root@localhost ~]#

To display the searched word in color
#grep –color root /etc/passwd

[root@localhost ~]# grep --color root /etc/passwd
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
[root@localhost ~]#

Leave a Reply

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