≡ Menu

grep in Bash

How do I use grep command in Bash?

The grep command searches the given files for lines containing a match to a given pattern list. In other words, use the grep command to search words or strings in a text files. When it finds a match in a file, it will display those line on screen.

grep examples in bash

The syntax is as follows:

grep 'word-to-search' filename
egrep 'word1|word2' /path/to/filename

Examples

Search for word vivek in /etc/passwd file, enter:
grep vivek /etc/passwd
Sample outputs:

vivek:x:500:100::/home/vivek:/bin/bash

Search for word vivek or priyanka in /etc/passwd file, enter:
egrep -w 'vivek|priyanka' /etc/passwd
Search all files in directory /nas/project for words ‘main’:
egrep -R 'main' *
OR limit search to word only
egrep -Rw 'main' *
Highlight words with color:
egrep --color -R 'main' *

Recommend readings:

Share this tutorial on:

Your support makes a big difference:
I have a small favor to ask. More people are reading the nixCraft. Many of you block advertising which is your right, and advertising revenues are not sufficient to cover my operating costs. So you can see why I need to ask for your help. The nixCraft, takes a lot of my time and hard work to produce. If you use nixCraft, who likes it, helps me with donations:
Become a Supporter →    Make a contribution via Paypal/Bitcoin →   

Don't Miss Any Linux and Unix Tips

Get nixCraft in your inbox. It's free:



{ 0 comments… add one }
Security: Are you a robot or human?

Leave a Comment

You can use these HTML tags and attributes: <strong> <em> <pre> <code> <a href="" title="">


   Tagged with: , , , , , , , , , , ,