How to use Basic Regular Expression with grep command on Linux

Regular expressions are special text strings that used to search for and match patterns in text. To make the search expression more specific, it can work together with the grep command. The grep command is the General Regular Expression Parser; it searches a file for strings matching a given regular expression, and by default it the prints out any line containing a string that matches. There are many useful options which can be set for grep which affect it output. This examples will show how to use caret ^ and dollar sign $ to print more specific output. This examples has been tested on Redhat Enterprise Linux 6 server. It may works on CentOS as well.

The caret ^ is meta-characters that respectively match the empty string at the beginning of a line.

Anchor : line begins with...

Meanwhile, the dollar sign $ is a meta-characters that respectively match the empty string at the end of a line.

Anchor : line ends with...

Examples :
1. Print all usernames that begin with the letter e :

[root@rhel6 ~]# grep '^e' /etc/passwd
ehowstuff:x:503:503::/home/ehowstuff:/bin/bash

2. Print all usernames that begin with the letter g :

[root@rhel6 ~]# grep '^g' /etc/passwd
games:x:12:100:games:/usr/games:/sbin/nologin
gopher:x:13:30:gopher:/var/gopher:/sbin/nologin

3. Print all usernames that begin with the letter a :

[root@rhel6 ~]# grep '^a' /etc/passwd
adm:x:3:4:adm:/var/adm:/sbin/nologin
abrt:x:499:499::/etc/abrt:/sbin/nologin
apache:x:48:48:Apache:/var/www:/sbin/nologin

4. Print all lines that end with the letter h :

[root@rhel6 ~]# grep 'h$' /etc/passwd
root:x:0:0:root:/root:/bin/bash
mysql:x:27:27:MySQL Server:/var/lib/mysql:/bin/bash
test:x:500:500::/home/test:/bin/bash
sambauser1:x:501:501::/home/sambauser1:/bin/bash
ftpuser:x:502:502::/home/ftpuser:/bin/bash
ehowstuff:x:503:503::/home/ehowstuff:/bin/bash
testuser:x:504:504::/home/testuser:/bin/bash