Grep is a pattern-searching command of Linux. It is a much more intensive filter that has three members ‘grep’, ‘egrep’, and fgrep utility. Grep command searches in a file linewise and works on record level not by field type. it searches string or pattern in files and show output in which the string or pattern occurs.

Grep Syntax :

grep options pattern filename(s)

The options value is not compulsory. you can take help from manual page of grep in Linux .

# man grep

It take imput as a standard input an gives output to standard output or redirect to any file.

Grep command in Linux with examples :

(1) grep techtransit /etc/passwd

Output :
techtransit:x:1000:1000:techtransit:/home/techtransit:/bin/bash

Above command will show if pattern techtransit is available in the /etc/passwd file .

(2) who | grep techtransit

who command will show who is logged on and with grep option will see if techtransit user is logged in . If the output of the command is null , means pattern searched for does not produce any match in the give file.

grep option example :

(1) with -c option will not show the lines where the matches occur . It will displays the count of occurrence of pattern in files .

# grep -c “techtransit” /etc/passwd /etc/group

Output :

[root@srv1 ~]# grep -c “techtransit” /etc/passwd /etc/group
/etc/passwd:1
/etc/group:2

(2) -n option will show line number along with matched record .

[root@srv1 ~]# grep -n “techtransit” /etc/passwd /etc/group

Output:

/etc/passwd:22:techtransit:x:1000:1000:techtransit:/home/techtransit:/bin/bash
/etc/group:11:wheel:x:10:techtransit
/etc/group:40:techtransit:x:1000:

(3) -l will show only filename where the string will find or matched . Below screenshot showing all above three example.

grep option example

(4) -i or –ignore-case will ignores the case for pattern matching. simple grep option will match exact pattern but with -i option , it will ignore caps and small letter. shown below example difference with and without ignore case.

Grep option ignore case

(5) -e exp : through this option we can pass multiple expressions to match. Below is the syntax.

grep -e “pattern1” -e “pattern2” searchfile

Multiple expression with Grep Command

By Sachin G

I am a professional freelance contributor and founder of tech transit. Love to write and lover of education, culture, and community. I have been using it, setting, supporting, and maintaining it since 2009.Linux rocks! Sachin G Follow me on LinkedIn and x formerly twitter