Searching for a pattern in Linux with example – Grep command

Grep is a pattern-searching command of Linux. It is a much more intensive 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 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 with examples :

(1) grep techtransit /etc/passwd

Output :

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 :

[[email protected] ~]# grep -c “techtransit” /etc/passwd /etc/group

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

[[email protected] ~]# grep -n “techtransit” /etc/passwd /etc/group



(3) -l will show only filename where the will 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 multiple expressions to match. Below is the syntax.

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

Multiple expression with Grep Command

About Sachin Gupta

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. rocks!

Have any Question or Comment?

Leave a Reply

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