Grep, egrep and fgrep commands in linux/unix with detailed examples



grep, egrep, fgrep - prints the lines with the search pattern


grep Searches the pattern in a file for the lines matching the specified pattern
egrep Advanced grepping where more than one pattern matching lines can be searched from a file using regular expressions
fgrep Faster version of grepping, dosn't support regular expressions

Syntax:

grep [options] "search pattern" <filename>

Examples:

1.

grep "foo" /home/abc/


Searches for the pattern foo in the directory abc.

2.
grep -R "foo" /home/abc/

Searches for the pattern foo in the directory and its sub directories recursively.

3.
grep -i "foo" /home/abc/

Searches for the patterns foo, Foo, fOo, foO, FOo, fOO, FoO, FOO in the directory abc. -i is used for case insensitive searches.

4.
grep -w "foo" /home/abc/

Searches for the word pattern foo in the directory abc. In this case the searched pattern is an exact word with name foo.

5.
grep -w "foo|bar" /home/abc/

Searches for the exact word patterns foo and bar. If any of the words gets matched, output will be displayed.

6.
grep -A2 "Alpha" abc.txt

It will display the next 2 lines after the search pattern.

7.
grep -B2 "Beta" abc.txt

It will display the previous 2 lines of the search pattern.

8.
grep -C2 "Gamma" abc.txt

It will display the previous 2 lines and next 2 lines of the search pattern.

9.
grep -v "Dog" abc.txt

It will search for all the lines that does not contain Dog in it. 

10.
grep -c "Cat" abc.txt

It will give the number of lines that matched the search pattern.

11.
grep -n "Num" abc.txt

It will display the line number along with the line that matches the search pattern.

12.
grep --color "Color" abc.txt

It will display the matched line in color. 

Related linux commands


List all the content using ls command
Search files and directories using find command
Know about Stream Editor commands